Why am I getting a NPE after reading a json file into my object?

carlWheezer :

I'm trying to read data out of a json file into my family class. When I try accessing the data I get a NPE

Gson gson = new Gson();

    try (Reader reader = new FileReader("family.json")) {

        Family family = gson.fromJson(reader, Family.class);
        System.out.println(family.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }

Family class

public class Family {
List<Person> people;

Person class

public class Person {
private String firstname;
private String lastname;

json file

{ "members" : [
{"firstname":"asdf", "lastname":"asdf"}, 
{"firstname":"qwer", "lastname":"qwer"}, 
{"firstname":"fghj", "lastname":"fghj"}
]

}

Any help/tips would be appreciated

Code_Mode :

You are getting NPE because, json file is having members list and mapped Family class has list of 'people'.

Change people list to members in Family class,

List<Person> members;

Hope it helps.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=328480&siteId=1