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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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();
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.