0

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.

Rahul
  • 895
  • 1
  • 13
  • 26
  • Maybe https://stackoverflow.com/questions/34623053/how-to-get-array-of-objects-with-gson-retrofit helps? – Stefan Mar 14 '20 at 12:08
  • will retrofit work on data read from a file, i have a option of editing the json format, as the data is stored in a local file. – Rahul Mar 14 '20 at 12:14
  • 1
    For testing, make a copy of your class where you use String str = "[{\"code\":\"24\",\"name\"... "; so you don't have to worry about the file. Also remove all the district stuff, to make the problem smaller and more focused on the (current) json issue. – Stefan Mar 14 '20 at 12:18

2 Answers2

1

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

Ervin Szilagyi
  • 14,274
  • 2
  • 25
  • 40
  • reading the file as FileReader throws an error of file not found, its in the resource folder. But i can read it as input stream no error is thrown, what edit should i make to it to read as input stream. – Rahul Mar 14 '20 at 12:53
  • 1
    `new FileReader("path_to_my_json.json");` - you can pass any absolute path here and it should be able to read your file with no issues (as long as the file is readable and we have the correct permissions for it). – Ervin Szilagyi Mar 14 '20 at 12:57
  • i tried reading the file by giving the relative path, or as classLoader, when reading as stream i can get the data but not as the file. Its a maven project the file is in src/main/resources. Also this reference might help for better understanding of situation https://stackoverflow.com/a/23547760/7419457 – Rahul Mar 14 '20 at 14:10
0

You have two options. Instead of using BufferReader, you can use FileReader like in below. By using FileReader, you have written cleaner code than before.

  1. Convert JSON file to Java object
    Gson gson = new Gson();
    StatesModel StatesModel = gson.fromJson(new FileReader("C:\\myfile.json"), StatesModel.class);
  1. Convert JSON string to Java object
    Gson gson = new Gson();
    String json = '{"code": "24", "name": "Rajsathan", "districts": [ {"code":"1", "name":"Jodhpur"}, {"code":"2", "name":"Nagore"}]}';
    StatesModel StatesModel = gson.fromJson(json, StatesModel.class);   
burak isik
  • 395
  • 5
  • 6
  • request you to read the comment thread of Ervin's Answer, below. – Rahul Mar 14 '20 at 19:10
  • 1
    You said that Reading the file as FileReader throws an error of file not found. This problem causes from you not FileReader class. So check your file path again. – burak isik Mar 14 '20 at 19:46