7

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=="
}

?

Sam Berry
  • 7,394
  • 6
  • 40
  • 58
Mohamed
  • 193
  • 3
  • 10

1 Answers1

11

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)

StaxMan
  • 113,358
  • 34
  • 211
  • 239
  • from the code in the question, it's clear that 'json' is a File object, containing the JSON text – Graham Griffiths Aug 27 '13 at 15:08
  • Correct -- I did not specify type since it can come from multiple sources (or even be JSON `byte[]` or `String`). @ImtiazAhmad check out Jackson javadocs for possible types to learn more. – StaxMan Aug 27 '13 at 17:44
  • I am facing just the opposite of this problem. I want to create a json file like user.json. with multiple root level values. But when I run the mapper.writeValue() method, it overwrites over older values. Can anyone help. – Shashank Garg Sep 04 '17 at 10:38
  • @ShashankGarg yes: ObjectMapper.writer().writeValues(dst) gives you `SequenceWriter` to do what you want – StaxMan Sep 07 '17 at 04:16