java - the best way to write multiple lists back to a single JsonArray

advertisements

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.

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:

[
{"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:

  1. Create a custom implementation of WriterBasedJsonGenerator (or any JsonGenerator you use) that modifies the behaviour a bit:
    public MyJsonGenerator extends WriterBasedJsonGenerator {
        @Override
        public void writeStartArray () {// do nothing
        }

        @Override
        public void writeEndArray () {// do nothing
        }
    }
  1. Than before writing the first ArrayList I would do

    generator.writeRaw ('[');
    

Before the next lists

generator.writeRaw (',');

And after the last list

generator.writeRaw (']');