获取json中数据和json数组根据其中一个属性进行分类重组

     String a="{'code':100,'data':{'grdbl':100.0,'bxl':646,'fwl':0,'mytsl':0}}";
        //先把String对象转换成json对象
        JSONObject object=JSONObject.fromObject(a);
        System.out.println(object.get("code"));
        System.out.println(object.getJSONObject("data"));
        System.out.println(object.getJSONObject("data").get("grdbl"));
        System.out.println(object.getJSONObject("data").get("bxl"));

///////////////////////////////////上面获取json中数据,下面是jsonArray中数据
        /*[
	        {
		        'otitle':'会',
		        'source':'7'
	        },
	        {
		        'otitle':'不会',
		        'source':'3'
	        }
          ]
         取出jsonArray中的值*/
        String str ="[{'otitle':'会','source':'7'},{'otitle':'不会','source':'3'}]";
        //1.把字符串类型的json数组对象转化JSONArray
        JSONArray jsonArray=JSONArray.fromObject(str);
        //2、循环遍历这个数组
        for(int i=0;i

重组json格式(JS写法)

let arr=[
        {
            "title":"值班",
            "name": "勤务工作",
            "number":2,
            "type": "待建设"
        },
        {
            "title":"值班",
            "name": "值班时间",
            "number":2,
            "type": "待建设"
        },
        {
            "title":"备勤",
            "name": "静态备勤",
            "number":2,
            "type": "已建设"
        },
		{
            "title":"备勤",
            "name": "动态备勤",
            "number":2,
            "type": "待建设"
        }
	];
//大括号{}创建一个对象  []数组
var map = {},dest = [];
for(var i = 0; i < arr.length; i++){
    var ai = arr[i];
    if(!map[ai.title]){
        dest.push({
            title: ai.title,
            data: [ai]
        });
        map[ai.title] = ai;
    }else{
        for(var j = 0; j < dest.length; j++){
            var dj = dest[j];
            if(dj.title == ai.title){
                dj.data.push(ai);
                break;
            }
        }
    }
}
console.log(JSON.stringify(dest));

获取json中数据和json数组根据其中一个属性进行分类重组_第1张图片

返回格式如下

[{
		"title": "值班",
		"data": [{
				"title": "值班",
				"name": "勤务工作",
				"number": 2,
				"type": "待建设"
			},
			{
				"title": "值班",
				"name": "值班时间",
				"number": 2,
				"type": "待建设"
			}
		]
	},
	{
		"title": "备勤",
		"data": [{
				"title": "备勤",
				"name": "静态备勤",
				"number": 2,
				"type": "已建设"
			},
			{
				"title": "备勤",
				"name": "动态备勤",
				"number": 2,
				"type": "待建设"
			}
		]
	}
]

使用java分类并且排序json

package org.example;

import com.alibaba.fastjson.JSON;

import java.util.*;

public class GroupJSON {
    public static void main(String[] args) {
        String jsonList = "[{\"model_flag\":\"1\",\"mxmc\":\"周三接待\",\"title\":\"唯一的A\",\"count(1)\":\"4\"},{\"model_flag\":\"1\",\"mxmc\":\"小区巡防\",\"title\":\"唯一的A\",\"count(1)\":\"3\"},{\"model_flag\":\"1\",\"mxmc\":\"纠纷调解\",\"title\":\"唯二的B\",\"count(1)\":\"3\"},{\"model_flag\":\"1\",\"mxmc\":\"境外人员\",\"title\":\"唯二的B\",\"count(1)\":\"3\"}]";
        //要格式化  不然出现下面状况等于号=情况
        System.out.println(JSON.toJSONString(sortGroupByFiled(jsonList,"title","model_flag")));

        List> list = (List>) JSON.parse(jsonList);
        System.out.println(sortGroupByFiled2(list,"title","model_flag"));
    }


    /**
     * 方式1:直接使用HashMap取出来所有分组,在进行分组排序,组内排序
     * 传入 String类型json返回list
     */
    public static List> sortGroupByFiled(String jsonList,String groupField,String sortField) {
        List> list = (List>) JSON.parse(jsonList);

        //定义一个要返回的新的List
        List> returnList = new ArrayList<>();
        Iterator iterator = list.iterator();
        Map>> hashMap = new HashMap<>();
        while (iterator.hasNext()) {
            Map tmp = (Map) iterator.next();
            String groupTitle1s = tmp.get(groupField).toString();
            if (hashMap.containsKey(groupTitle1s)) {
                ArrayList> list2 = hashMap.get(groupTitle1s);
                list2.add(tmp);
            } else {
                hashMap.put(groupTitle1s, new ArrayList<>());
                ArrayList> list1 = hashMap.get(groupTitle1s);
                list1.add(tmp);
            }
        }

        //取出来key进行排序
        List keySet = new ArrayList<>(hashMap.keySet());
        Collections.sort(keySet);
        Iterator iterator1 = keySet.iterator();
        while (iterator1.hasNext()) {
            String title = (String) iterator1.next();
            Map newMap = new HashMap<>();
            List> list2 = hashMap.get(title);
            Collections.sort(list2, (o1, o2) -> {
                if (Integer.valueOf(o1.get(sortField).toString()) > Integer.valueOf(o2.get(sortField).toString())) {
                    return 1;
                } else if (Integer.valueOf(o1.get(sortField).toString()) < Integer.valueOf(o2.get(sortField).toString())) {
                    return -1;
                } else {
                    return 0;
                }
            });
            newMap.put(groupField, title);
            newMap.put("list", list2);
            returnList.add(newMap);
        }
        return returnList;
    }





    /**
     * 方式2:使用TreeMap先分组排序,在组内排序
     * 传入list类型json返回list
     */
    public static List> sortGroupByFiled2(List> list,String groupField,String sortField) {
        //这里使用treeMap的自动排序机制,对groupNo进行排序
        TreeMap>> treeMap = new TreeMap<>();
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            Map tmp = (Map) iterator.next();
            String groupTitle1s = tmp.get(groupField).toString();
            if (treeMap.containsKey(groupTitle1s)) {
                ArrayList> list2 = treeMap.get(groupTitle1s);
                list2.add(tmp);
                Collections.sort(list2, (o1, o2) -> {
                    if (Integer.valueOf(o1.get(sortField).toString()) > Integer.valueOf(o2.get(sortField).toString())) {
                        return 1;
                    } else if (Integer.valueOf(o1.get(sortField).toString()) < Integer.valueOf(o2.get(sortField).toString())) {
                        return -1;
                    } else {
                        return 0;
                    }
                });
            } else {
                treeMap.put(groupTitle1s, new ArrayList>());
                ArrayList> list1 = treeMap.get(groupTitle1s);
                list1.add(tmp);
            }
        }
        //定义一个要返回的新的List
        List> returnList = new ArrayList<>();
        Iterator iter = treeMap.entrySet().iterator();
        while (iter.hasNext()) {
            Map newMap = new HashMap<>();
            Map.Entry>> entry = (Map.Entry>>) iter.next();
            String keytitle = entry.getKey();
            newMap.put(groupField, keytitle);
            newMap.put("list", entry.getValue());
            returnList.add(newMap);
        }
        return returnList;
    }

}

分组排序后的json

[{
	"title": "唯一的A",
	"list": [{
		"model_flag": "1",
		"mxmc": "周三接待",
		"count(1)": 4,
		"title": "唯一的A"
	}, {
		"model_flag": "1",
		"mxmc": "小区巡防",
		"count(1)": 3,
		"title": "唯一的A"
	}]
}, {
	"title": "唯二的B",
	"list": [{
		"model_flag": "1",
		"mxmc": "纠纷调解",
		"count(1)": 3,
		"title": "唯二的B"
	}, {
		"model_flag": "1",
		"mxmc": "境外人员",
		"count(1)": 3,
		"title": "唯二的B"
	}]
}]

再分享个JSONUtil


package org.example.utils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaoleilu.hutool.util.ObjectUtil;

public class JSONUtils {
	/**
	 * json数组的一个字段,复制为另一个名字
	 *
	 * @param jsonStr
	 * @param fromTo
	 *            :key json数组中对象的字段名 ;value :将key复制,并修改名字
	 * @return
	 * @author lizhenming
	 * @date 2019年1月14日
	 */
public static JSONArray fieldsConversio(String jsonStr, Map fromTo) {
        if (ObjectUtil.isNull(fromTo)) {
        return JSON.parseArray(jsonStr);
        }
        JSONArray _resulearr = JSON.parseArray(jsonStr);

        for (Iterator iterator = _resulearr.iterator(); iterator.hasNext();) {
        JSONObject _oJsonObject = (JSONObject) iterator.next();

        for (Map.Entry entry : fromTo.entrySet()) {
        String _from = entry.getKey();
        String _to = entry.getValue();
        if (ObjectUtil.isNotNull(_oJsonObject.get(_from))) {
        _oJsonObject.put(_to, _oJsonObject.get(_from));
        }
        }
        }

        return _resulearr;
        }

/**
 * JSON字符串分组
 *
 * @param jsonStr
 * @param byKey
 * @param byName
 * @return
 * @author lizhenming
 * @date 2019年1月14日
 */
public static JSONArray groupBy(String jsonStr, String byKey, String byName) {
        if (StringUtils.isBlank(jsonStr)) {
        return null;
        }
        Map map = new HashMap();
        JSONArray _resuleArray = new JSONArray();
        JSONArray _befortArray = JSON.parseArray(jsonStr);
        for (Iterator iterator = _befortArray.iterator(); iterator.hasNext();) {
        JSONObject _item = (JSONObject) iterator.next();
        // 如果JSON分组不存在

        if (StringUtils.isBlank(map.get(_item.get(byKey)))) {
        JSONObject _group_obj = new JSONObject();
        JSONArray _group_list = new JSONArray();
        _group_obj.put(byKey, _item.get(byKey));
        _group_obj.put(byName, _item.get(byName));
        _group_list.add(_item);
        _group_obj.put("data", _group_list);
        map.put(_item.get(byKey), "exist");
        _resuleArray.add(_group_obj);
        } else {
        for (int _i = 0; _i < _resuleArray.size(); _i++) {
        JSONObject _temp_obj = _resuleArray.getJSONObject(_i);
        if (_temp_obj.get(byKey).equals(_item.get(byKey))) {
        _temp_obj.getJSONArray("data").add(_item);
        }
        }
        }

        }
        return _resuleArray;
        }

/**
 * JSON分组
 *
 * @param jsonStr
 * @param byKey
 * @return
 * @author lizhenming
 * @date 2019年1月14日
 */
public static JSONArray groupBy(String jsonStr, String byKey) {
        if (StringUtils.isBlank(jsonStr)) {
        return null;
        }
        Map map = new HashMap();
        JSONArray _resuleArray = new JSONArray();
        JSONArray _befortArray = JSON.parseArray(jsonStr);
        for (Iterator iterator = _befortArray.iterator(); iterator.hasNext();) {
        JSONObject _item = (JSONObject) iterator.next();
        // 如果JSON分组不存在

        if (StringUtils.isBlank(map.get(_item.get(byKey)))) {
        JSONObject _group_obj = new JSONObject();
        JSONArray _group_list = new JSONArray();
        _group_obj.put(byKey, _item.get(byKey));

        _group_list.add(_item);
        _group_obj.put("data", _group_list);
        map.put(_item.get(byKey), "exist");
        _resuleArray.add(_group_obj);
        } else {
        for (int _i = 0; _i < _resuleArray.size(); _i++) {
        JSONObject _temp_obj = _resuleArray.getJSONObject(_i);
        if (_temp_obj.get(byKey).equals(_item.get(byKey))) {
        _temp_obj.getJSONArray("data").add(_item);
        }
        }
        }

        }
        return _resuleArray;
        }

/**
 * JSON分组
 *
 * @param befortArray
 * @param byKey
 * @return
 * @author lizhenming
 * @date 2019年1月14日
 */
public static JSONArray groupBy(JSONArray befortArray, String byKey) {
        if (ObjectUtil.isNull(befortArray)) {
        return null;
        }
        Map map = new HashMap();
        JSONArray _resuleArray = new JSONArray();

        for (Iterator iterator = befortArray.iterator(); iterator.hasNext();) {
        JSONObject _item = (JSONObject) iterator.next();
        // 如果JSON分组不存在
        if (StringUtils.isBlank(map.get(_item.get(byKey)))) {
        JSONObject _group_obj = new JSONObject();
        JSONArray _group_list = new JSONArray();
        _group_obj.put(byKey, _item.get(byKey));
        _group_list.add(_item);
        _group_obj.put("data", _group_list);
        map.put(_item.get(byKey), "exist");
        _resuleArray.add(_group_obj);
        } else {
        for (int _i = 0; _i < _resuleArray.size(); _i++) {
        JSONObject _temp_obj = _resuleArray.getJSONObject(_i);
        if (_temp_obj.get(byKey).equals(_item.get(byKey))) {
        _temp_obj.getJSONArray("data").add(_item);
        }
        }
        }

        }
        return _resuleArray;
        }

}

pom为

  
      com.xiaoleilu
      hutool-all
      3.0.1
    

 

你可能感兴趣的:(json)