Deserialize JSON to ArrayList<POJO> using Jackson
You can deserialize directly to a list by using the TypeReference
wrapper. An example method:
public static <T> T fromJSON(final TypeReference<T> type, final String jsonPacket) { T data = null; try { data = new ObjectMapper().readValue(jsonPacket, type); } catch (Exception e) { // Handle the problem } return data;}
And is used thus:
final String json = "";Set<POJO> properties = fromJSON(new TypeReference<Set<POJO>>() {}, json);
Another way is to use an array as a type, e.g.:
ObjectMapper objectMapper = new ObjectMapper();MyPojo[] pojos = objectMapper.readValue(json, MyPojo[].class);
This way you avoid all the hassle with the Type object, and if you really need a list you can always convert the array to a list by:
List<MyPojo> pojoList = Arrays.asList(pojos);
IMHO this is much more readable.
And to make it be an actual list (that can be modified, see limitations of Arrays.asList()
) then just do the following:
List<MyPojo> mcList = new ArrayList<>(Arrays.asList(pojos));