ali haider
ali haider

Reputation: 20202

write Java List to JSON Array via Jackson

I am using Jackson for JSON serialization. I am trying to convert a Java List (containing string values) to a JSON array. I tried the following approaches (issues given below for each)

1. write array elements using JsonGenerator's writeString

final JsonGenerator generator = factory.createGenerator(output, JsonEncoding.UTF8);
  generator.writeStartArray();
        for (String arg: argsList) {
            generator.writeStartObject();
            log.info("arg value is {}", arg);
            generator.writeString(arg);
            generator.writeEndObject();
        }
        generator.writeEndArray();

Exception

Can not write a string, expecting field name (context: Object)

I get the exception from "generator.writeString(arg)". I cannot use writeStringField.

object mapper

ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(out, argsList);
            final byte[] argsBytes = out.toByteArray();
            generator.writeFieldName("args");
            generator.writeObjectField("args", argsBytes) 

This creates the array as a String and not an array within the JSON object (which is what I am trying to achieve). Any suggestions would be welcome.

End state (trying to achieve):

{
"args":["abc","def","ghi","jkl","mno"]
}

Upvotes: 6

Views: 10807

Answers (1)

weston
weston

Reputation: 54781

By starting/ending an object around each array entry what you are doing is trying to make invalid json:

{
    "args":[{"abc"},{"def"},{"ghi"},{"jkl"},{"mno"}]
}

And the generator is rightly stopping you from doing this.

Just write the strings directly into the array:

final JsonGenerator generator = factory.createGenerator(output, JsonEncoding.UTF8);
generator.writeStartArray();
for (String arg: argsList) {
    generator.writeString(arg);
}
generator.writeEndArray();

Upvotes: 7

Related Questions