2

I have some data that is put into a List and I am trying to use the ObjectMapper class from Jackson to map them into a single string so that I can then convert them into a JsonNode to return. The issue is that I do not want to manually hardcode commas for the mapper to distinguish each element.

The list returned from the database looks like this:

0: {"someKey": "someVal"}
1: {"someKey2": "someVal2"}
2: {"someKey3": "someVal3"}
List<String> responseList = dao.getDetails(something, something2);

for(String row : responseList){
 responseString += row;
}

jsonNode = mapper.readTree(responseString);

The resulting jsonNode of that would be :

{"someKey": "someVal"}

the objectmapper ignores the other two values because the string doesn't have any commas to distinguish them. How can I get a single JsonNode response for a list of strings without having to manually insert commas and brackets? thanks!!

1 Answer 1

4

Instead of joining everything into a String, you can parse individually each row and add it manually to an ArrayNode, like this:

List<String> responseList = Arrays.asList(
        "{\"someKey\": \"someVal\"}",
        "{\"someKey2\": \"someVal2\"}",
        "{\"someKey3\": \"someVal3\"}");

ObjectMapper mapper = new ObjectMapper();
ArrayNode arr = mapper.createArrayNode();
for (String row : responseList) {
    arr.add(mapper.readTree(row));
}
System.out.println(arr);
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.