0

if i have simple json with

{   
    "age":29,
    "messages":["msg 1","msg 2","msg 3"],
    "name":"mkyong"
}

i use this code

public class JacksonExample {

    public static void main(String[] args) {

    ObjectMapper mapper = new ObjectMapper();

    try {

        // read from file, convert it to user class
        User user = mapper.readValue(new File("c:\\user.json"), User.class);

        // display to console
        System.out.println(user);

    } catch (JsonGenerationException e) {

        e.printStackTrace();

    } catch (JsonMappingException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

  }

}

and get, one object. but what if i have

{
    "age":29,
    "messages":["msg 1","msg 2","msg 3"],
    "name":"alice"
}
{
    "age":18,
    "messages":["msg 4","msg 5","msg 6"],
    "name":"bob"
} 

how can i get all objects from one json file and add their to list? sorry for my bad english

2
  • 1
    The thing you're trying to parse is not a valid JSON. You should wrap it in array or something, like this: [{"age":29, ... },{"age":18, ... }]. On how to parse an array, you can read here Commented May 20, 2014 at 12:41
  • try this link Commented May 20, 2014 at 12:51

2 Answers 2

1

If you have a JSON array of Users you can de-serialize:

  • As a Collection of User:

    om.readValue("myFile", new TypeReference<Collection<User>>() {});

  • As an array of User

    om.readValue("myFile", User[].class);

You're probably going to need your JSON file to be fixed, as pointed out by SimY4.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this :

Class<?> clz = Class.forName(type);
JavaType listType = mapper.getTypeFactory().constructCollectionType(List.class, clz);
List <T> record = mapper.readValue(json, listType);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.