簡體   English   中英

將JSON響應轉換為List <T>

[英]Convert JSON response into 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(){
         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>
你有什么建議?

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

為此你可以使用令牌,以便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  }

嵌套的"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());

如果你有權訪問創建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());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM