0

I’m currently writing Java client code that gets a JSON response from a rest service. For my JSON response, I need to deserialize it to a pojo. If the JSON’s outer most wrappers are square brackets that enclose a list of objects, what Jackson annotation can I use to load it to an array or ArrayList?

The JSON looks like this:

[{"key1": "val1"}, {"key2": "val2"}, {"key3": "val3"}]
lanadelrey
  • 441
  • 1
  • 4
  • 10
  • have you had a look at this? https://stackoverflow.com/questions/9829403/deserialize-json-to-arraylistpojo-using-jackson – Elie Nassif Apr 11 '19 at 05:28
  • Possible duplicate of [Deserialize JSON to ArrayList using Jackson](https://stackoverflow.com/questions/9829403/deserialize-json-to-arraylistpojo-using-jackson) – Adam Michalik Apr 11 '19 at 05:36
  • That link assumes you have the JSON string. My JSON is coming from an http response in Spring. I thought an annotation of some sort would be needed to get the JSON and convert it to an ArrayList. – lanadelrey Apr 11 '19 at 05:46

2 Answers2

0

Jackson can unmarshall json directly to your object, vise-versa.

public void givenJsonArray_whenDeserializingAsArray_thenCorrect() 
  throws JsonParseException, JsonMappingException, IOException {

    ObjectMapper mapper = new ObjectMapper();
    List<MyDto> listOfDtos = Lists.newArrayList(
      new MyDto("a", 1, true), new MyDto("bc", 3, false));
    String jsonArray = mapper.writeValueAsString(listOfDtos);

    // [{"stringValue":"a","intValue":1,"booleanValue":true},
    // {"stringValue":"bc","intValue":3,"booleanValue":false}]

    MyDto[] asArray = mapper.readValue(jsonArray, MyDto[].class);
    assertThat(asArray[0], instanceOf(MyDto.class));
}

source:https://www.baeldung.com/jackson-collection-array

Elie Nassif
  • 464
  • 4
  • 11
0

you can try this

String json = "[{\"key1\": \"val1\"}, {\"key2\": \"val2\"}, {\"key3\": \"val3\"}]";
ObjectMapper mapper = new ObjectMapper();
ArrayList<Map<String,String>> list = mapper.readValue(json, Object.class);
for (Map map : list)
    for (Object key :map.keySet()) 
        System.out.println("key: "+key.toString()+" value:"+map.get(key));
//result
//key: key1 value:val1
//key: key2 value:val2
//key: key3 value:val3
葭诩Rex
  • 1
  • 2