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"}]
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));
}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.