且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Jackson - 将 Java 列表写入 json 数组的***方式

更新时间:2022-10-17 21:35:51

这太复杂了,Jackson 通过其 writer 方法处理列表就像处理常规对象一样.假设我没有误解您的问题,这对您来说应该很好用:

public void writeListToJsonArray() 抛出 IOException {最终列表list = new ArrayList(2);list.add(new Event("a1","a2"));list.add(new Event("b1","b2"));最终 ByteArrayOutputStream out = new ByteArrayOutputStream();final ObjectMapper mapper = new ObjectMapper();mapper.writeValue(out, list);final byte[] data = out.toByteArray();System.out.println(new String(data));}

I want to use jackson to convert a ArrayList to a JsonArray.

Event.java : this is the java bean class with two fields "field1", "field2" mapped as JsonProperty.

My goal is:

Convert

ArrayList<Event> list = new ArrayList<Event>();
    list.add(new Event("a1","a2"));
    list.add(new Event("b1","b2"));

To

[
{"field1":"a1", "field":"a2"},
{"field1":"b1", "field":"b2"}
]

The way I can think of is: 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());
}

I am looking for something like:

generator.write(out, list)  

this directly convert the list to json array format and then write it to outputstream "out".

even greedier:

generator.write(out, list1)

generator.write(out, list2)

this will just convert/add in the list1, list2 into a single json array. then write it to "out"

This is overly complicated, Jackson handles lists via its writer methods just as well as it handles regular objects. This should work just fine for you, assuming I have not misunderstood your question:

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));
}