7

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"]
}
4
  • So, you want a JSON object with a single key named args, containing your list? Is that right? Why don't you create a class, with a single field named args, containing your list, and serialize an instance of that class? Commented Mar 17, 2017 at 18:19
  • will try that - I was hoping I could achieve the same through the generator. Commented Mar 17, 2017 at 18:24
  • You can achieve every valid json through the generator. If if you do try a serializer (which is a fine suggestion), please at least finish this question so we don't have just another "Don't do that, use a serializer" question/answer. Commented Mar 17, 2017 at 18:42
  • I had to remove the writeStart/endObject which fixed the issue - thanks everyone Commented Mar 17, 2017 at 18:52

1 Answer 1

9

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.