How to create a JSON Object using Object Model in Java?

JavaJSONObject Oriented ProgrammingProgramming

The javax.json.JsonObject interface can represent an immutable JSON object value and provides an unmodifiable map view to the JSON object name/value mappings. A JsonObject instance can be created from an input source using the static method readObject() of javax.json.JsonReader class and also can be created using the static method createObjectBuilder() of javax.json.Json class.

Syntax

public static JsonObjectBuilder createObjectBuilder()

Example

import java.io.*;
import javax.json.*;
public class JsonObjectTest {
   public static void main(String[] args) throws Exception {
      JsonObjectBuilder builder = Json.createObjectBuilder();
      builder.add("Name", "Adithya");
      builder.add("Designation", "Python Developer");
      builder.add("Company", "TutorialsPoint");
      builder.add("Location", "Hyderabad");
      JsonObject data = builder.build();
      StringWriter sw = new StringWriter();
      JsonWriter jw = Json.createWriter(sw);
      jw.writeObject(data);
      jw.close();
      System.out.println(sw.toString());
   }
}

Output

{"Name":"Adithya","Designation":"Python Developer","Company":"TutorialsPoint","Location":"Hyderabad"}
raja
Published on 21-Oct-2019 14:31:47
Advertisements