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!!
CodePudding user response:
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);