将JSON响应转换为List <t>

时间:2016-12-20 18:38:25

标签: java android json list gson

我是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(){
         return "Account{"+
         "ac_id="+ac_id+
         ", user_id="+user_id+
         ", title="+title+'}';

    }

}

当我在课堂上发表回复时,我得到了:

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

现在我需要将这两个值放入List<Account> 你有什么建议?

4 个答案:

答案 0 :(得分:5)

JSONObject data = new JSONObject(response);
JSONArray accounts = data.getJSONArray("data");    
List<Account> 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));
}

答案 1 :(得分:3)

为此您可以使用令牌,以便gson可以理解自定义类型...

TypeToken<List<Account>> token = new TypeToken<List<Account>>(){};
List<Account > accountList= gson.fromJson(response, token.getType());

for(Account account : accountList) {
      //some code here for looping  }

答案 2 :(得分:1)

嵌套"data"密钥毫无意义。如果你可以修复你的JSON,你应该改为。

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

然后这将有效。

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

或者,第一个"data"也不是必需的 如果您可以将您的JSON作为帐户列表......

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

这将有效

List<Account> accountList = new Gson()
    .fromJson(response, new TypeToken<ArrayList<Account>>(){}.getType());

答案 3 :(得分:0)

如果您可以访问创建JSON的位置,我认为您应该这样做:

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

然后转换它,只需使用此代码:(其中jsonString是上面的字符串)

List<Account> accountList = new Gson().fromJson(jsonString, new TypeToken<ArrayList<Account>>(){}.getType());