java - 将多个列表重新编写回单个JsonArray的最佳方法 [英] java - the best way to write multiple lists back to back to a single JsonArray

查看:96
本文介绍了java - 将多个列表重新编写回单个JsonArray的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是将多个列表重新转换回单个JsonArray的最佳方法是什么。这些列表即将发布,所以我不想或者我不能将所有列表(list1 - listn)合并到一个大列表中,然后使用Jackson将合并列表写入JsonArray。

My question is what's the best way to convert multiple lists back to back into a single 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.

转换

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 

单个jsonArray:

To a single jsonArray:

[
{"field1":"a1", "field2":"a2"},
{"field1":"b1", "field2":"b2"},
{"field1":"c1", "field2":"c2"},
{"field1":"d1", "field2":"d2"},
......
{"field1":"n1", "field2":"n2"}
]


推荐答案

在一天结束时,我发现在Jackson中没有这样的方法允许你直接将两个列表重新写回JsonArray。您可以使用自己的实现writeStartArray()writeEndArray()实现JsonGenerator,或者更简单,您可以定义startArray和endArray,并自己构造jsonArray

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. 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

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+ "]";

所以代码大致如下:

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)

这篇关于java - 将多个列表重新编写回单个JsonArray的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆