JSONArray properties combined in the same field

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/GoSaint/article/details/89177922
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());
        }
    }
}

 

Guess you like

Origin blog.csdn.net/GoSaint/article/details/89177922