I want to convert an Array into a Json Object like
String[] array = {"value1", "value2"};
into
{
"array": ["value1", "value2"]
}
I am using Spring (Jackson XML).
I tried:
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode jsonNode = objectMapper.createObjectNode();
String[] array = {"value1", "value2"};
jsonNode.put("array", Arrays.toString(array));
System.out.print(jsonNode.toString());
But the result is
{
"array":"[value1, value2]"
}
And not
{
"array":["value1", "value2"]
}
what I want to get.
You are converting Array of strings into string and adding it to json object
String[] array = {"value1", "value2"};
String arr = Arrays.toString(array) //converting array into string
Just add the array directly to ObjectNode using putArray
ArrayNode arrayNode = jsonNode.putArray("array");
Arrays.stream(array).forEach(str->arrayNode.add(str));
or you can also use addAll directly by converting array into ArrayNode
jsonNode.putArray("array").addAll(objectMapper.valueToTree(array));
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