In my app, I'm working with objects like this:
public class User {
private String name;
private int age;
}
I make a call to an API, and the response looks like:
{
response: {
result: [
{
name: x
age: y
},
{
name: x
age: y
},
...
}
}
Somehow, I'd like to call User[] users = restTemplate.getForObject(url, ...)
and get my list of users.
However, I'm unsure of how to parse the json response and create a list of User
s using Jackson.
Anyone have suggestions?
CodePudding user response:
Jackson can deal with generic collections with POJO values:
try {
Map<String, Map<String, List<User>>> result = mapper.readValue(response, new TypeReference<Map<String, Map<String, List<User>>>>() {});
List<User> users = result.get("response").get("result");
for (User user : users) {
System.out.println(user.getName());
}
} catch (Exception e) {
e.printStackTrace();
}
CodePudding user response:
public class User {
private String name;
private int age;
}
class Response{
private User[] result;
// omitted getter and setter
}
class OuterResponse{
private Response response;
// omitted getter and setter
}
OuterResponse outerResponse = restTemplate.getForObject(url, ...);
User[] users=outerResponse.getResponse().getResult();