Android 通过GSON将JSONArray转换为自定义对象的ArrayList

Android 通过GSON将JSONArray转换为自定义对象的ArrayList,android,json,gson,Android,Json,Gson,我得到一个json字符串形式的响应。在响应中,一个字段可以是对象数组或简单对象 例如 类型1 [{"0":1, "1":"name1", "id":1, "name":"name1"} , {"0":2, "1":"name2", "id":2, "name":"name2"}] 类型2 {"0":1, "1":"name1", "id":1, "name":"name1"} 为了处理这种情况,我创建了两个模型类,一个用于对象数组,另一个用于单个对象 有什么聪明的方法来处理这个问题。这将是我

我得到一个json字符串形式的响应。在响应中,一个字段可以是对象数组或简单对象 例如

类型1

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

{"0":1, "1":"name1", "id":1, "name":"name1"}
为了处理这种情况,我创建了两个模型类,一个用于对象数组,另一个用于单个对象


有什么聪明的方法来处理这个问题。

这将是我的方法

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();
    }
试试看{
JSONArray JSONArray=新的JSONArray(jsonString);
for(int i=0;i
好的。所以,你想使用GSON

首先,转到并创建relaventonepojo类

以下是模型类:

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

}
现在,如果响应中有JSONArray,则不需要创建第二个模型类。您可以尝试以下方法获取
ArrayList

Type collectionType=new-TypeToken(){}.getType();
ArrayList tripList=tripListGson.fromJson(此处为JSON数组字符串,collectionType);
我希望它能帮助你

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