Skip to content

Copy all values List to Jackson JsonGenerator Array directly instead of looping over it

I am creating a JSON file using the Jackson JsonGenerator for which I need to add the elements from List<String>. This List consists of the JSON Fragments which needs to be added to my final JSON file.

As of now, I am looping over the List<String> and adding them to my Jackson JsonGenerator writeRaw one-by-one. This is working fine as of now. However, my List can have 1000s or more values then I do not wish to loop and add one by one. Rather than that, I am finding a way to directly add the array to the JsonGeneator array. I wanted to know if there is a way to directly copy the array something like this:

jsonGenerator.writeArray("eventList",eventsList);

Following is the code I have currently:

public class JacksonTest {
    public static void main(String[] args) throws IOException {

        List<String> eventsList = new ArrayList<>();
        eventsList.add("{n" + "  "isA": "Customer",n" + "  "name": "Rise Against",n" + "  "age": "2000"n" + "}");
        eventsList.add("{n" + "  "isA": "Owener",n" + "  "name": "Linkin Park",n" + "  "age": "2ßß8"n" + "}");
        eventsList.add("{n" + "  "isA": "Customer",n" + "  "name": "Breaking Benjamin",n" + "  "age": "2005"n" + "}");

        StringWriter jsonObjectWriter = new StringWriter();
        JsonGenerator jsonGenerator = new JsonFactory().createGenerator(jsonObjectWriter).useDefaultPrettyPrinter();
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("schema","2.0");
        jsonGenerator.writeStringField("date","2021-06-22");


        //Current Approach
        jsonGenerator.writeFieldName("eventList");
        jsonGenerator.writeStartArray();

        //Add events from the list one by one
        eventsList.forEach(event -> {
            try {
                jsonGenerator.writeRaw(event + ",");
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        jsonGenerator.writeEndArray();
        jsonGenerator.writeEndObject();
        jsonGenerator.close();
        jsonGenerator.flush();

        System.out.println(jsonObjectWriter.toString());
    }
}

As you can observe from the above code, I am looping over the List<String> and adding them to JsonGeneator one-by-one. Can someone please suggest if there is a way to directly add the List<String> to JsonGenerator so that I can skip the looping part.

Something similar is available in JSONObject here we can directly add the list:

final JSONObject doc = new JSONObject();
doc.put("schemaVersion", 2.0);
final JSONObject eventListAsJson = new JSONObject();
eventListAsJson.put("eventList", eventsList);
doc.put("eventList", eventListAsJson);

Any help or suggestion would be really appreciated.

Answer

As indicated by @Thomas I did the following to add the elements from LIST to my JsonGenerator:

jsonGenerator.writeRaw(String.join(",", eventsList));