2

I am getting a response in the form of json string.In response one field could be array of object or a simple object for eg.

Type 1.

[{"0":1, "1":"name1", "id":1, "name":"name1"} , {"0":2, "1":"name2", "id":2, "name":"name2"}]

Type 2.

{"0":1, "1":"name1", "id":1, "name":"name1"}

To handle this case I have created two model classes one for array of object and one for single object.

Is there any smart way to handle this.

Bhavesh Patadiya
  • 25,740
  • 15
  • 81
  • 107
Sonu
  • 21
  • 4

2 Answers2

1

Ok. So, you want to use GSON.

First, Go to http://www.jsonschema2pojo.org/ and create relavent one POJO Class.

Below would be the Model Class :

Example.java

public class Example {

@SerializedName("0")
@Expose
private Integer _0;
@SerializedName("1")
@Expose
private String _1;
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("name")
@Expose
private String name;

/**
* 
* @return
* The _0
*/
public Integer get0() {
return _0;
}

/**
* 
* @param _0
* The 0
*/
public void set0(Integer _0) {
this._0 = _0;
}

/**
* 
* @return
* The _1
*/
public String get1() {
return _1;
}

/**
* 
* @param _1
* The 1
*/
public void set1(String _1) {
this._1 = _1;
}

/**
* 
* @return
* The id
*/
public Integer getId() {
return id;
}

/**
* 
* @param id
* The id
*/
public void setId(Integer id) {
this.id = id;
}

/**
* 
* @return
* The name
*/
public String getName() {
return name;
}

/**
* 
* @param name
* The name
*/
public void setName(String name) {
this.name = name;
}

}

Now, you do not need to create second Model class if there are JSONArray in response. you can try out below ways to get your ArrayList<Example>.

Type collectionType = new TypeToken<ArrayList<Example>>() {}.getType();
ArrayList<Example> tripList = tripListGson.fromJson(YOUR JSON ARRAY STRING HERE, collectionType);

I hope it would help you out.

Bhavesh Patadiya
  • 25,740
  • 15
  • 81
  • 107
0

This will be my approach

try {
        JSONArray jsonArray = new JSONArray(jsonString);
        for(int i =0; i < jsonArray.length(); i++)
        {
            parseToObject(jsonArray.getJSONObject(0));// parse you JSONObject to model object here
        }
    } catch (JSONException e) {
        // it the json is not array it throws exception so you can catch second case here
        parseToObject(jsonString);
        e.printStackTrace();
    }
Ravi Gadipudi
  • 1,446
  • 1
  • 17
  • 30