我想使用 Jackson 将 ArrayList 转换为 JsonArray。
Event
是 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"}
]
我能想到的办法是:
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”。
这太复杂了,Jackson 通过其 writer 方法处理列表,就像处理常规对象一样。假设我没有误解你的问题,这应该对你有用:
public void writeListToJsonArray() throws IOException {
final List<Event> list = new ArrayList<Event>(2);
list.add(new Event("a1","a2"));
list.add(new Event("b1","b2"));
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(out, list);
final byte[] data = out.toByteArray();
System.out.println(new String(data));
}
我找不到@atrioom所说的
toByteArray()
,所以我使用StringWriter
,请尝试:
public void writeListToJsonArray() throws IOException {
//your list
final List<Event> list = new ArrayList<Event>(2);
list.add(new Event("a1","a2"));
list.add(new Event("b1","b2"));
final StringWriter sw =new StringWriter();
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(sw, list);
System.out.println(sw.toString());//use toString() to convert to JSON
sw.close();
}
或者只是使用
ObjectMapper#writeValueAsString
:
final ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(list));
在 objectMapper 中,我们有 writeValueAsString() ,它接受对象作为参数。我们可以传递对象列表作为参数来获取字符串。
List<Apartment> aptList = new ArrayList<Apartment>();
Apartment aptmt = null;
for(int i=0;i<5;i++){
aptmt= new Apartment();
aptmt.setAptName("Apartment Name : ArrowHead Ranch");
aptmt.setAptNum("3153"+i);
aptmt.setPhase((i+1));
aptmt.setFloorLevel(i+2);
aptList.add(aptmt);
}
mapper.writeValueAsString(aptList)
使用 Jackson 最简单的方法是:
List<YourObject> yourList = new ArrayList<>();
// yourList - fill it with the data
final ObjectMapper mapper = new ObjectMapper();
try {
System.out.println(mapper.writeValueAsString(yourList));
} catch (JsonProcessingException e) {
e.printStackTrace();
}