“Como escrever um arquivo json usando java” Respostas de código

Escreva a string json para arquivar em java

// Write JSON string to a file
try (FileWriter file = new FileWriter("fileName.json")) {
  file.write(data); // data is a JSON string here
  file.flush();
} catch (IOException e) {
  e.printStackTrace();
}
Black Wolf

Como escrever um arquivo json usando java

import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
 
public class WriteJSONExample
{
    @SuppressWarnings("unchecked")
    public static void main( String[] args )
    {
        //First Employee
        JSONObject employeeDetails = new JSONObject();
        employeeDetails.put("firstName", "Lokesh");
        employeeDetails.put("lastName", "Gupta");
        employeeDetails.put("website", "howtodoinjava.com");
         
        JSONObject employeeObject = new JSONObject(); 
        employeeObject.put("employee", employeeDetails);
         
        //Second Employee
        JSONObject employeeDetails2 = new JSONObject();
        employeeDetails2.put("firstName", "Brian");
        employeeDetails2.put("lastName", "Schultz");
        employeeDetails2.put("website", "example.com");
         
        JSONObject employeeObject2 = new JSONObject(); 
        employeeObject2.put("employee", employeeDetails2);
         
        //Add employees to list
        JSONArray employeeList = new JSONArray();
        employeeList.add(employeeObject);
        employeeList.add(employeeObject2);
         
        //Write JSON file
        try (FileWriter file = new FileWriter("employees.json")) {
            //We can write any JSONArray or JSONObject instance to the file
            file.write(employeeList.toJSONString()); 
            file.flush();
 
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//Update pom.xml with json-simple maven dependency.
Chathumal Sangeeth

Respostas semelhantes a “Como escrever um arquivo json usando java”

Perguntas semelhantes a “Como escrever um arquivo json usando java”

Mais respostas relacionadas para “Como escrever um arquivo json usando java” em Java

Procure respostas de código populares por idioma

Procurar outros idiomas de código