Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write Java List to JSON Array via Jackson

Tags:

java

json

arrays

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"]
}
like image 799
ali haider Avatar asked Mar 17 '17 18:03

ali haider


People also ask

How can we convert a list to the JSON array in Java?

We can convert a list to the JSON array using the JSONArray. toJSONString() method and it is a static method of JSONArray, it will convert a list to JSON text and the result is a JSON array.

How do I convert a JSON list to Jackson?

We can convert a List to JSON array using the writeValueAsString() method of ObjectMapper class and this method can be used to serialize any Java value as a String.

How do I add a list to a JSON Object in Java?

JSONObject obj = new JSONObject(); List<String> sList = new ArrayList<String>(); sList. add("val1"); sList. add("val2"); obj. put("list", sList);


1 Answers

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();
like image 129
weston Avatar answered Oct 09 '22 23:10

weston