Going through some reading, I saw below example for Jackson Streaming API. They are writing for one object (kind of one map). Can any one please help me on how to write multiple objects. Like a List of Maps.
jsonFactory jfactory = new JsonFactory();
/*** write to file ***/
JsonGenerator jGenerator = jfactory.createJsonGenerator(new File(
"c:\\user.json"), JsonEncoding.UTF8);
jGenerator.writeStartObject(); // {
jGenerator.writeStringField("name", "mkyong"); // "name" : "mkyong"
jGenerator.writeNumberField("age", 29); // "age" : 29
jGenerator.writeFieldName("messages"); // "messages" :
jGenerator.writeStartArray(); // [
jGenerator.writeString("msg 1"); // "msg 1"
jGenerator.writeString("msg 2"); // "msg 2"
jGenerator.writeString("msg 3"); // "msg 3"
jGenerator.writeEndArray(); // ]
jGenerator.writeEndObject(); // }
jGenerator.close();
I tried looping and got below result.
{“Item1label1”:”Item1value1”,”Item1label2”:”Item1value2"} {“Item2label1”:”Item2value1”,”Item2label2”:”Item2value2"}
But this is not a valid JSON. As something is missing in between two objects. What code has to be made to make it valid JSON.
Below is an example of writing a large array of objects ( HashMap
here but could be any other) with writePOJOField
method. I use jackson-core and jackson-databind (see https://github.com/FasterXML/jackson ).
// given
ByteArrayOutputStream stream = new ByteArrayOutputStream();
JsonFactory jfactory = new JsonFactory(new ObjectMapper());
JsonGenerator jGenerator = jfactory.createGenerator(stream, JsonEncoding.UTF8);
// when
jGenerator.writeStartObject();
jGenerator.writeStringField("name", "Tom");
jGenerator.writeNumberField("age", 25);
jGenerator.writeFieldName("objects");
jGenerator.writeStartArray();
IntStream.range(0, 3).forEach(it -> {
try {
jGenerator.writePOJO(new HashMap<String, String>() {{
put("key1", "value1");
put("key2", "value2");
}});
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
});
jGenerator.writeEndArray();
jGenerator.writeFieldName("strings");
jGenerator.writeStartArray();
jGenerator.writeString("textX");
jGenerator.writeString("textY");
IntStream.range(0, 3).forEach(it -> {
try {
jGenerator.writeString("text-" + it);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
});
jGenerator.writeEndArray();
jGenerator.writeNullField("nullField");
jGenerator.writeEndObject();
jGenerator.close();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.