Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson - Json to POJO With Multiple Entries

Tags:

java

json

jackson

I know If the file User.json has

{
  "name" : { "first" : "Joe", "last" : "Sixpack" },
  "gender" : "MALE",
  "verified" : false,
  "userImage" : "Rm9vYmFyIQ=="
}

I can construct a single User object like this :

User user = mapper.readValue(new File("user.json"), User.class);

But how do I construct a list of objects if the file User.json has :

{
  "name" : { "first" : "Joe", "last" : "Sixpack" },
  "gender" : "MALE",
  "verified" : false,
  "userImage" : "Rm9vYmFyIQ=="
},
{
  "name" : { "first" : "Jane", "last" : "Austen" },
  "gender" : "FEMALE",
  "verified" : false,
  "userImage" : "DFREWEWE=="
}

?

like image 598
Mohamed Avatar asked Aug 12 '11 20:08

Mohamed


1 Answers

Multiple ways: if you have a JSON array of these, you can do:

User[] users = mapper.readValue(json, User[].class);

or, if it is just a sequence of root level values you can do:

Iterator<User> it = mapper.readValues(json, User.class);

and iterate over values (add to a List or such)

like image 94
StaxMan Avatar answered Sep 23 '22 00:09

StaxMan