3

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.

1
  • It shoud work properly if You won't call Arrays.toString and instead pass the array itself. Commented Feb 13, 2020 at 18:18

1 Answer 1

2

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));
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.