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

Mario Stoilov
  • 3,411
  • 5
  • 31
  • 51
mechanikos
  • 771
  • 12
  • 32
  • 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](http://stackoverflow.com/questions/6349421/how-to-use-jackson-to-deserialise-an-array-of-objects) – Alex May 20 '14 at 12:41
  • try this [link](http://stackoverflow.com/a/18959730/1283215) – Hussain Akhtar Wahid 'Ghouri' May 20 '14 at 12:51

2 Answers2

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.

Community
  • 1
  • 1
Mena
  • 47,782
  • 11
  • 87
  • 106
0

Try this :

Class<?> clz = Class.forName(type);
JavaType listType = mapper.getTypeFactory().constructCollectionType(List.class, clz);
List <T> record = mapper.readValue(json, listType);
Vimal Bera
  • 10,346
  • 4
  • 25
  • 47