java怎么去除JSON数组的重复值

如题所述

对最佳回答进行修改,假设原始Json数组是这样的

原始JSONArry:[{"Value":"15153129877","Key":"09770985-9869-11e7-9c0d-fa163ef28f43"},{"Value":"15153129877","Key":"09770985-9869-11e7-9c0d-fa163ef28f43"}]

工具类如下:

/**
 * 根据Key去重复
 * @param array
 */
public static JSONArray delRepeatIndexid(JSONArray array) {
    JSONArray arrayTemp = new JSONArray();
    int num = 0;
    for(int i = 0;i < array.size();i++){
        if(num==0){
            arrayTemp.add(array.get(i));
        }else{
            int numJ = 0;
            for(int j = 0;j < arrayTemp.size(); j++){
                JSONObject newJsonObjectI = (JSONObject)array.get(i);
                JSONObject newJsonObjectJ = (JSONObject)arrayTemp.get(j);
                String index_idI = newJsonObjectI.get("Key").toString();
                String valueI = newJsonObjectI.get("Value").toString();
                String index_idJ = newJsonObjectJ.get("Key").toString();
                if(index_idI.equals(index_idJ)){
                    arrayTemp.remove(j);
                    JSONObject newObject = new JSONObject();
                    newObject.put("Key", index_idI);
                    newObject.put("Value", valueI);
                    arrayTemp.add(newObject);
                    break;
                }
                numJ++;
            }
            if(numJ-1 == arrayTemp.size()-1){
                arrayTemp.add(array.get(i));
            }
        }
        num++;
    }
    return arrayTemp;
}

处理结果

数据处理后JSONArry:[{"Value":"15153129877","Key":"09770985-9869-11e7-9c0d-fa163ef28f43"}]

完毕!!!!

温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-12-05
代码如下:
/**
* 去重复index_id项合并value值
* @param args
*/
public static JSONArray delRepeatIndexid(JSONArray array) {

JSONArray arrayTemp = new JSONArray();

int num = 0;
for(int i = 0;i < array.size();i++){
if(num==0){
arrayTemp.add(array.get(i));
}else{
int numJ = 0;
for(int j = 0;j < arrayTemp.size(); j++){
JSONObject newJsonObjectI = (JSONObject)array.get(i);
JSONObject newJsonObjectJ = (JSONObject)arrayTemp.get(j);
String index_idI = newJsonObjectI.get("index_id").toString();
String valueI = newJsonObjectI.get("value").toString();
String timeI = newJsonObjectI.get("time").toString();
String itemidI = newJsonObjectI.get("itemid").toString();

String index_idJ = newJsonObjectJ.get("index_id").toString();
String valueJ = newJsonObjectJ.get("value").toString();

if(index_idI.equals(index_idJ)){
int newValue = Integer.parseInt(valueI) + Integer.parseInt(valueJ);
arrayTemp.remove(j);
JSONObject newObject = new JSONObject();
newObject.put("index_id", index_idI);
newObject.put("itemid", itemidI);
newObject.put("time", timeI);
newObject.put("value", newValue);
arrayTemp.add(newObject);
break;
}
numJ++;
}
if(numJ-1 == arrayTemp.size()-1){
arrayTemp.add(array.get(i));
}
}

num++;
}
return arrayTemp;
}本回答被网友采纳
第2个回答  2016-12-05
自己写个比较方法直接删除就行。

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网