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

?

1 Answer 1

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)

4
  • from the code in the question, it's clear that 'json' is a File object, containing the JSON text Aug 27, 2013 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, 2013 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. Sep 4, 2017 at 10:38
  • @ShashankGarg yes: ObjectMapper.writer().writeValues(dst) gives you SequenceWriter to do what you want
    – StaxMan
    Sep 7, 2017 at 4:16

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.