将JSON响应转换为List< T> [英] Convert JSON response into List<T>

查看:84
本文介绍了将JSON响应转换为List< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是GSON的新手。我需要将以下JSON响应转换为List。



JSON响应:

 data:[{
data:{
ac_id:000,
user_id:000,
title:AAA
}
},{
data:{
ac_id:000,
user_id: 000,
title:AAA
}
}]
}

我有一个类来投射数据



帐户。 java

  public class Account {

public int ac_id;
public int user_id;
public String title;

@Override
public String toString(){
returnAccount {+
ac_id =+ ac_id +
,user_id =+ user_id +
,title =+ title +'}';

}

}

我的班级的回应是:

$ p $ [帐户{ac_id =000,user_id =000,title = AAA},帐户{ac_id =000,user_id =000,title =AAA}]

现在我需要将这两个值放入 List< Account>

您有什么建议?

解决方案

  JSONObject data = new JSONObject(response); 
JSONArray accounts = data.getJSONArray(data);
清单<帐户> accountList = new Gson()。fromJson(accounts.toString(),new TypeToken< ArrayList< Account>>(){}。getType());

如果您无法更改您的JSON响应以删除内部数据键,则可以使用以下命令:

  Gson gson = new Gson(); 
ArrayList< Account> accountList = new ArrayList< Account>();
JSONArray accounts = data.getJSONArray(data);
for(int i = 0; i< accounts.length(); i ++){
JSONObject a = accounts.getJSONObject(i).getJSONObject(data);
accountList.add(gson.fromJson(a.toString(),Account.class));
}


I am new to GSON. I need to convert the following JSON response into a List.

JSON response:

{
    "data": [{
        "data": {
            "ac_id": "000",
            "user_id": "000",
            "title": "AAA"
        }
    }, {
        "data": {
            "ac_id": "000",
            "user_id": "000",
            "title": "AAA"
        }
    }]
}

I have a class to cast data

Account. java

public class Account {

     public int ac_id;
     public int user_id;
     public String title;

    @Override
    public String toString(){
         return "Account{"+
         "ac_id="+ac_id+
         ", user_id="+user_id+
         ", title="+title+'}';

    }

}

When I cast the response with my class I get:

[Account{ac_id="000", user_id="000", title="AAA"}, Account{ac_id="000", user_id="000", title="AAA"}]

Now I need to put these two values into a List<Account>.
What do you suggest?

解决方案

JSONObject data = new JSONObject(response);
JSONArray accounts = data.getJSONArray("data");    
List<Account> accountList = new Gson().fromJson(accounts.toString(), new TypeToken<ArrayList<Account>>(){}.getType());

If you cannot change your JSON response to remove the inner "data" key, you can use this:

Gson gson = new Gson();
ArrayList<Account> accountList = new ArrayList<Account>();
JSONArray accounts = data.getJSONArray("data");  
for (int i = 0; i < accounts.length(); i++) {
  JSONObject a = accounts.getJSONObject(i).getJSONObject("data");
  accountList.add(gson.fromJson(a.toString(), Account.class));
}

这篇关于将JSON响应转换为List&lt; T&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆