How to serialize a JSON object with JsonWriter using Object Model in Java?


The javax.json.JsonWriter interface can write a JSON object or array structure to an output source. The class javax.json.JsonWriterFactory contains methods to create JsonWriter instances. A factory instance can be used to create multiple writer instances with the same configuration. We can create writers from output source using the static method createWriter() of javax.json.Json class.

Syntax

public static JsonWriter createWriter(Writer writer)

In the below example, we can serialize a JSON object using the JsonWriter interface.

Example

import java.io.StringWriter;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonWriter;
public class JsonWriterTest {
   public static void main(String[] args) {
      JsonObject jsonObj = Json.createObjectBuilder()
                 .add("name", "Adithya")
                 .add("age", 25)
                 .add("salary", 40000)
                 .add("address",
                      Json.createObjectBuilder().add("street", "Madhapur")
                                                .add("city", "Hyderabad")
                                                .add("zipCode", "500084")
                                                .build()
                      )
                 .add("phoneNumber",
                      Json.createArrayBuilder().add("9959984000")
                                               .add("7702144400")
                                               .build()
                     )
                 .build();

      StringWriter stringWriter = new StringWriter();
      JsonWriter writer = Json.createWriter(stringWriter);
      writer.writeObject(jsonObj);
      writer.close();
      System.out.println(stringWriter.getBuffer().toString());
   }
}

Output

{"name":"Adithya","age":25,"salary":40000,"address":{"street":"Madhapur","city":
"Hyderabad","zipCode":"500084"},"phoneNumber":["9959984000","7702144400"]}

raja
raja

e

Updated on: 08-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements