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"]
}
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.
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.
JSONObject obj = new JSONObject(); List<String> sList = new ArrayList<String>(); sList. add("val1"); sList. add("val2"); obj. put("list", sList);
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With