亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用java將jsonobjects添加到jsonarray時避免重復

使用java將jsonobjects添加到jsonarray時避免重復

Helenr 2021-05-31 09:20:45
我有一個對象列表,正在轉換為 JSONArray。我正在遍歷 JSONObjects 并制作一個 JSONObjects 數組?,F在,我想避免將重復對象插入到 JSONArray 中。請在下面找到我的java代碼。JSONArray responseArray1 = new JSONArray();if (!itemList.isEmpty()){  jsonArray = new JSONArray(itemList);  for (int i = 0; i < jsonArray.length(); i++)  {    JSONObject jsonObj = jsonArray.getJSONObject(i);    JSONObject responseObj = new JSONObject();    String attr_label = jsonObj.optString("attr_label");    if(StringUtils.equalsIgnoreCase(attr_label, "long_description")) {        long_description = jsonObj.optString("value");    }    else if(StringUtils.equalsIgnoreCase(attr_label, "description")) {        description = jsonObj.optString("value");    }    responseObj.put("id", jsonObj.opt("id")); // i will get duplicate id    responseObj.put("code", jsonObj.opt("code")); // i will get duplicate code    responseObj.put("long_description", long_description);    responseObj.put("description", description);    responseArray1.put(responseObj);  }}請找到我的實際 jsonArray :[     {        "code":"xyaz",      "attr_label":"long_description",      "id":"12717",      "value":"Command Module"   },   {        "code":"xyaz",      "attr_label":"description",      "id":"12717",      "value":"Set Point Adjustment"   },]我期待像下面的 jsonArray :[     {        "code":"xyaz",      "id":"12717",      "long_description":"Command Module"      "description" : "Set Point Adjustment"   }]
查看完整描述

2 回答

?
繁星點點滴滴

TA貢獻1803條經驗 獲得超3個贊

創建一個臨時數組列表并在該 arrayList 中添加唯一代碼并檢查它是否已存在于 arrayList 中然后不要再放這個


String code = jsonObj.opt("code");

if(!arrayList.contains(code))

{

    arrayList.add(code);

    responseObj.put("id", jsonObj.opt("id")); 

    responseObj.put("code", jsonObj.opt("code")); 

    responseObj.put("long_description", long_description);

    responseObj.put("description", description);

}


查看完整回答
反對 回復 2021-06-02
  • 2 回答
  • 0 關注
  • 417 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號