合并JSONArray中的属性相同的字段

package com.cmos.listener;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class JSONTest {

    public static void main(String[] args) {
        JSONArray array=new JSONArray();
        JSONObject j1=new JSONObject();
        j1.put("id","1");
        j1.put("name","lily");
        j1.put("count","198");
        JSONObject j2=new JSONObject();
        j2.put("id","1");
        j2.put("name","lily");
        j2.put("count","2");
        JSONObject j3=new JSONObject();
        j3.put("id","2");
        j3.put("name","lily");
        j3.put("count","300");
        array.add(j1);
        array.add(j2);
        array.add(j3);
        System.out.println(array);
        //合并
        JSONArray newArray=new JSONArray();
        Map<String, JSONObject> map = new HashMap<>();
        for(Object json:array){
            JSONObject  obj= (JSONObject)json;
            JSONObject  newObj= map.get(obj.getString("id"));
            if(newObj!=null){
                long countOfOld=Long.parseLong((String)newObj.get("count"));
                long countOfNew=Long.parseLong((String) obj.get("count"));
                long count=countOfOld+countOfNew;
                newObj.put("count",count);
            }else {
                map.put(obj.getString("id"),obj);
                newArray.add(obj);
            }
        }
        Iterator<Map.Entry<String, JSONObject>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, JSONObject> next = iterator.next();
            System.out.println(next.getKey()+"==="+next.getValue());
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值