Search code examples
javajsongsonpojo

Converting a list of json objects to java object using gson, gets null


The Json data that i have.

[

    {

        "code": "24",

        "name": "Rajsathan",

        "districts": [

                {"code":"1",

                 "name":"Jodhpur"},

                {"code":"2",

                 "name":"Nagore"}

                ]

    }

]

Reading the data from a file as inputstream.

BufferedReader br = new BufferedReader(new InputStreamReader(in));
Gson gson = new Gson();
String temp = null;
String total = null;
try {
  while((temp = br.readLine()) != null) {
    total+=temp;
  }
} catch (Exception e){
    e.printStactTrace();
}

Now i tried many different ways to convert this data to java objects, but got null when passing the complete string total or malformed json error when converting each stream from streamreader.

StatesModel data = gson.fromJson(total, StatesModel.class);

// as its a list of json 
Type collectionType = new TypeToken<Collection<StatesModel>>(){}.getType();
Collection<StatesModel> json_data = gson.fromJson(total, collectionType);

But both do not work.

The Java classes for statesModel is defined as below.

public class StatesModel {

    @SerializedName("code")
    public String code;

    @SerializedName("name")
    public String name;

    @SerializedName("districts")
    public List<DistrictModel> districts;

    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public List<DistrictModel> getDistricts() {
        return districts;
    }
    public void setDistricts(List<DistrictModel> districts) {
        this.districts = districts;
    }

}

And the districts class model being.

public class DistrictModel {

    @SerializedName("code")
    public String code;

    @SerializedName("name")
    public String name;

    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}

what would be the right way to convert this data to iterable javaObjects.


Solution

  • Your JSON starts with a [ this means that we would want an array of StatesModel. This can be read from a file like this:

    Reader reader = new FileReader("path_to_my_json.json");
    
    Gson gson = new Gson();
    StatesModel[] statesModels = gson.fromJson(reader, StatesModel[].class);
    
    // do something with the array
    Stream.of(statesModels).forEach(System.out::println);
    

    StatesModel POJO:

    public class StatesModel {
        private String code;
        private String name;
        private List<DistrictModel> districts;
    
        public String getCode() {
            return code;
        }
    
        public void setCode(String code) {
            this.code = code;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public List<DistrictModel> getDistricts() {
            return districts;
        }
    
        public void setDistricts(List<DistrictModel> districts) {
            this.districts = districts;
        }
    
        @Override
        public String toString() {
            return "StatesModel{" +
                    "code='" + code + '\'' +
                    ", name='" + name + '\'' +
                    ", districts=" + districts +
                    '}';
        }
    }
    

    DistrictModel POJO:

    public class DistrictModel {
        private String code;
        private String name;
    
        public String getCode() {
            return code;
        }
    
        public void setCode(String code) {
            this.code = code;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            return "DistrictModel{" +
                    "code='" + code + '\'' +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
    

    Working code can be found on github: https://github.com/Ernyoke/gson-tutorial