[英]java - the best way to write multiple lists back to back to a single JsonArray
My question is what's the best way to convert multiple lists back to back into a single JsonArray. 我的问题是将多个列表重新转换回单个JsonArray的最佳方法是什么。 The lists are coming on the fly, so I don't want to or I can't have all the lists(list1 - listn) merged in a big list, then use Jackson to write the merged list to a JsonArray.
列表是动态的,所以我不想或者无法将所有列表(list1-listn)合并到一个大列表中,然后使用Jackson将合并后的列表写入JsonArray。
Convert 兑换
ArrayList<Event> list1 = new ArrayList<Event>();
list1.add(new Event("a1","a2"));
list1.add(new Event("b1","b2"));
ArrayList<Event> list2 = new ArrayList<Event>();
list2.add(new Event("c1","c2"));
list2.add(new Event("d1","d2"));
......
......listn
To a single jsonArray: 到单个jsonArray:
[
{"field1":"a1", "field2":"a2"},
{"field1":"b1", "field2":"b2"},
{"field1":"c1", "field2":"c2"},
{"field1":"d1", "field2":"d2"},
......
{"field1":"n1", "field2":"n2"}
]
I don't know Jackson
but looking at the API
I would do sth like this: 我不认识
Jackson
但是看着API
我会做的像这样:
WriterBasedJsonGenerator
(or any JsonGenerator
you use) that modifies the behaviour a bit: WriterBasedJsonGenerator
(或您使用的任何JsonGenerator
)的自定义实现, WriterBasedJsonGenerator
对该行为进行一些修改: public MyJsonGenerator extends WriterBasedJsonGenerator { @Override public void writeStartArray () {// do nothing } @Override public void writeEndArray () {// do nothing } }
Than before writing the first ArrayList
I would do 比写第一个
ArrayList
之前
generator.writeRaw ('[');generator.writeRaw('[');
Before the next lists 在下一个列表之前
generator.writeRaw (',');
And after the last list 在最后一个列表之后
generator.writeRaw (']');
At the end of the day, I found out that there is no such way in Jackson allowing you directly write two lists back to back into a JsonArray. 归根结底,我发现杰克逊(Jackson)中没有这样的方法,您无法直接将两个列表直接写回到JsonArray中。 You can either implement JsonGenerator with your own implementation writeStartArray() writeEndArray() OR even easier, you can just define the startArray and endArray, and construct the jsonArray by yourself
您可以使用自己的实现writeStartArray()writeEndArray()来实现JsonGenerator,或者甚至更简单,您可以定义startArray和endArray并自己构造jsonArray
private static final String JSON_ARRAY_START = "[" + LINE_BREAK;
private static final String JSON_ARRAY_COMMA = "," + LINE_BREAK;
private static final String JSON_ARRAY_END = LINE_BREAK+ "]";
so code will roughly look like: 因此代码大致如下所示:
write(JSON_ARRAY_START)
foreach list1
use objectMapper write every Event object
write(JSON_ARRAY_COMMA)
foreach list2
use objectMapper write every Event object
if it's not the last element in the list, write(JSON_ARRAY_COMMA)
write(JSON_ARRAY_END)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.