The Jackson data binding documentation indicates that Jackson supports deserialising \"Arrays of all supported types\" but I can\'t figure out the exact syntax for this.
you could also create a class which extends ArrayList
:
public static class MyList extends ArrayList<Myclass> {}
and then use it like:
List<MyClass> list = objectMapper.readValue(json, MyList.class);
First create a mapper :
import com.fasterxml.jackson.databind.ObjectMapper;// in play 2.3
ObjectMapper mapper = new ObjectMapper();
As Array:
MyClass[] myObjects = mapper.readValue(json, MyClass[].class);
As List:
List<MyClass> myObjects = mapper.readValue(jsonInput, new TypeReference<List<MyClass>>(){});
Another way to specify the List type:
List<MyClass> myObjects = mapper.readValue(jsonInput, mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class));
try {
ObjectMapper mapper = new ObjectMapper();
JsonFactory f = new JsonFactory();
List<User> lstUser = null;
JsonParser jp = f.createJsonParser(new File("C:\\maven\\user.json"));
TypeReference<List<User>> tRef = new TypeReference<List<User>>() {};
lstUser = mapper.readValue(jp, tRef);
for (User user : lstUser) {
System.out.println(user.toString());
}
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I was unable to use this answer because my linter won't allow unchecked casts.
Here is an alternative you can use. I feel it is actually a cleaner solution.
public <T> List<T> parseJsonArray(String json, Class<T> clazz) throws JsonProcessingException {
var tree = objectMapper.readTree(json);
var list = new ArrayList<T>();
for (JsonNode jsonNode : tree) {
list.add(objectMapper.treeToValue(jsonNode, clazz));
}
return list;
}
From Eugene Tskhovrebov
List<MyClass> myObjects = Arrays.asList(mapper.readValue(json, MyClass[].class))
This solution seems to be the best for me
First create an instance of ObjectReader which is thread-safe.
ObjectMapper objectMapper = new ObjectMapper();
ObjectReader objectReader = objectMapper.reader().forType(new TypeReference<List<MyClass>>(){});
Then use it :
List<MyClass> result = objectReader.readValue(inputStream);