JSON object parsing using retrofit2.0

241 views Asked by At

I'm trying to parse a JSON object using retrofit 2.0 following this guide, but it doesn't work. I think it's because of a difference in JSON format.

Here is a nested JSON object with the format:

{
    "SearchService": {
        "list_total_count": 531,
        "RESULT": {
            "CODE": "INFO-001",
            "MESSAGE": "SUCCESS"
        },
        "row": [{
            "ID": "1983",
            "NAME": "SAN",
            "NUM": "38",
        }, {
            "ID": "1984",
            "NAME": "DU",
            "NUM": "27",
        }]
    }
}

Here is class code using SerializedName:

RowList.java

public class RowList {
    @SerializedName("row")
    @Expose
    private ArrayList<Row> rows= new ArrayList<>();

    public ArrayList<Row> getRows() {
        return rows;
    }

    public void setRows(ArrayList<Row> rows) {
        this.rows= rows;
    }
}

Row.java

public class Row{

    @SerializedName("ID")
    @Expose
    private String id;

    @SerializedName("NAME")
    @Expose
    private String name;

    @SerializedName("NUM")
    @Expose
    private String num;

    /*getter setter*/

}
1

There are 1 answers

0
OneCricketeer On BEST ANSWER

Read that guide.

There are two approaches to create Model class. The first way is the manual approach, which requires you to learn how to use the Gson library. The second approach is you can also auto-generate the Java classes you need by capturing the JSON output and using jsonschema2pojo

Looks like you've attempted approach one, but haven't (yet?) tried reading over the Gson documentation.


Okay, you have a Row. That covers the objects within "row": [...], so you also need objects for the following:

  • "SearchService": {}
  • "RESULT": {}

I don't think the RowList class is necessary. List<Row> is fine.

For example,

class Result {
    @SerializedName("CODE")
    String code;
    @SerializedName("MESSAGE")
    String message;
}

class SearchService {
    @SerializedName("list_total_count")
    long count;
    @SerializedName("RESULT")
    Result result;
    @SerializedName("row")
    private ArrayList<Row> rows= new ArrayList<>();
}

(removed @Expose for conciseness)

Then, Retrofit would use Call<SearchService>