需求背景:
前端实现下拉列表的级联效果。mybaits单条查询1000次以上耗时为:0.2*1000=200秒
缩减时间:一次查询全部数据 0.2秒但是数据格式不满足条件.
结构为:
[
{
"channel_id": 1,
"channel_name": "张三",
"id": 11,
"company_name": "A公司"
},
{
"channel_id": 1,
"channel_name": "张三",
"id": 12,
"company_name": "B公司"
},
{
"channel_id": 1,
"channel_name": "张三",
"id": 13,
"company_name": "C公司"
},
{
"channel_id": 1,
"channel_name": "张三",
"id": 14,
"company_name": "D公司"
},
{
"channel_id": 2,
"channel_name": "李四",
"id": 21,
"company_name": "AA公司"
},
{
"channel_id": 2,
"channel_name": "李四",
"id": 22,
"company_name": "BB公司"
},
{
"channel_id": 2,
"channel_name": "李四",
"id": 23,
"company_name": "CC公司"
},
{
"channel_id": 2,
"channel_name": "李四",
"id": 24,
"company_name": "DD公司"
}
]
前端数据格式
[
{
"channel_id": 1,
"channel_name": "张三",
"data": [
{
"id": 11,
"company_name": "A公司"
},
{
"id": 12,
"company_name": "B公司"
},
{
"id": 13,
"company_name": "C公司"
},
{
"id": 14,
"company_name": "D公司"
},
]
},
{
"channel_id": 2,
"channel_name": "李四",
"data": [
{
"id": 21,
"company_name": "AA公司"
},
{
"id": 22,
"company_name": "BB公司"
},
{
"id": 23,
"company_name": "CC公司"
},
{
"id": 24,
"company_name": "DD公司"
},
]
}
]
方法
/**
* 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
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));
Object keyValue = _item.remove(byKey);
_item.remove(byName);
_group_list.add(_item);
_group_obj.put("data", _group_list);
map.put(keyValue, "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))) {
_item.remove(byKey);
_item.remove(byName);
_temp_obj.getJSONArray("data").add(_item);
}
}
}
}
return _resuleArray;
}