JsonGenerator is used to generate json content and writes JSON data to an output source in a streaming way.
How to create a JsonGenerator?
You can create JsonGenerator by passing an output stream as argument to createGenerator method of Json class.
Example
ByteArrayOutputStream bos = new ByteArrayOutputStream();
JsonGenerator jsonGenerator = Json.createGenerator(bos);
How to generate json content?
‘JsonGenerator’ class provides multiple write* method to write json content.
jsonGenerator.writeStartObject();
Writes json start object character.
jsonGenerator.writeStartArray("hobbies");
Writes the JSON name/start array character pair with in the current object context.
jsonGenerator.writeEnd();
Writes the end of the current context. If the current context is an array context, this method writes the end-of-array character (']'). If the current context is an object context, this method writes the end-of-object character ('}').
Find the below working application.
JsonGeneratorDemo.java
package com.sample.app;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.json.Json;
import javax.json.stream.JsonGenerator;
public class JsonGeneratorDemo {
public static void main(String args[]) throws IOException {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
try (JsonGenerator jsonGenerator = Json.createGenerator(bos);) {
jsonGenerator.writeStartObject();
jsonGenerator.write("id", 123);
jsonGenerator.write("name", "Krishna");
// Write nested json document
jsonGenerator.writeStartObject("address").write("street", "Chodeswari").write("city", "Bangalore")
.writeEnd();
// Write array content
jsonGenerator.writeStartArray("hobbies");
jsonGenerator.write("Cricket");
jsonGenerator.write("Chess");
jsonGenerator.writeEnd();
jsonGenerator.writeEnd();
}
String finalString = new String(bos.toByteArray());
System.out.println(finalString);
}
}
}
Output
{"id":123,"name":"Krishna","address":{"street":"Chodeswari","city":"Bangalore"},"hobbies":["Cricket","Chess"]}
No comments:
Post a Comment