Jackson - 将java列表写入json数组的最佳方式
我想使用jackson将ArrayList转换为JsonArray。
事件.java:这是java bean类,其中两个字段“field1”,“field2”映射为JsonProperty。
我的目标是:
转换
ArrayList<Event> list = new ArrayList<Event>();
list.add(new Event("a1","a2"));
list.add(new Event("b1","b2"));
自
[
{"field1":"a1", "field":"a2"},
{"field1":"b1", "field":"b2"}
]
我能想到的方法是:writeListToJsonArray():
public void writeListToJsonArray() throws IOException {
ArrayList<Event> list = new ArrayList<Event>();
list.add(new Event("a1","a2"));
list.add(new Event("b1","b2"));
OutputStream out = new ByteArrayOutputStream();
JsonFactory jfactory = new JsonFactory();
JsonGenerator jGenerator = jfactory.createJsonGenerator(out, JsonEncoding.UTF8);
ObjectMapper mapper = new ObjectMapper();
jGenerator.writeStartArray(); // [
for (Event event : list) {
String e = mapper.writeValueAsString(event);
jGenerator.writeRaw(usage);
// here, big hassles to write a comma to separate json objects, when the last object in the list is reached, no comma
}
jGenerator.writeEndArray(); // ]
jGenerator.close();
System.out.println(out.toString());
}
我正在寻找类似的东西:
generator.write(out, list)
这将直接将列表转换为json数组格式,然后将其写入输出流“out”。
更贪婪:
generator.write(out, list1)
generator.write(out, list2)
这将只是将list1,list2转换/添加到单个json数组中。然后将其写到“out”