How to create and write JSON array to a file in java?

Java 8Object Oriented ProgrammingProgramming

Java provides javax.json.Json package which contains classes to read a JSON array:

Example

import java.io.FileOutputStream;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonWriter;

public class JSONArrayToFile {
   public static void main(String args[]) throws Exception {
      JsonArray value = Json.createArrayBuilder()
         .add(Json.createObjectBuilder()
         .add("id", "1001")
         .add("Technology", "JavaFX"))
         .add(Json.createObjectBuilder()
         .add("id", "1002")
         .add("Technology", "OpenCV"))
         .build();
      System.out.println(value);
      JsonWriter writer = Json.createWriter(new FileOutputStream("sampleData"));
      writer.writeArray(value);
      writer.close();
   }
}

Output

["JavaFX","HBase","JOGL","WebGL"]
After deleting ::["JavaFX","HBase","JOGL"]
raja
Published on 09-Jan-2018 13:34:24
Advertisements