服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - 使用json字符串插入节点或者覆盖节点

使用json字符串插入节点或者覆盖节点

2021-11-13 11:25BugCounter Java教程

这篇文章主要介绍了使用json字符串插入节点或者覆盖节点的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

json字符串插入节点或者覆盖节点

jfdaJson是json字符串

?
1
2
3
4
JSONObject obj=JSONObject.parseObject(jfdaJson);
obj.put("dj",xydjDm);// 更新dj字段
obj.put("xydjMc",xydjMc);// 添加xydjMc字段
obj.toString();

json字符串转换成json增删查改节点

一、功能实现

1、节点树查询:

按ID查询树

2、节点新增:

?
1
2
http://host/tree_data/node/${treeId}
in: {node: {key: ..., ...}, parent: ${key}, sequ: ${sequ}}

3、节点修改

?
1
2
http://host/tree_data/node/${treeId}/${key}
in: {node: {key: ..., ...}}

4、节点删除

?
1
http://host/tree_data/node/${treeId}/${key}

二、数据表结构

使用json字符串插入节点或者覆盖节点

?
1
2
3
4
5
6
7
8
9
CREATE TABLE `catagory_tree`  (
  `id` bigint(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '分类树名称:PRODUCT:产品分类  GOODS:商品分类',
  `json_tree` text CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '直接存储ANTD树表的数据结构',
  `modify_staff` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `modify_time` datetime(0) NOT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `AK_uni_catagory_tree_name`(`name`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

三、json字符串

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
[{
 "id": 1,
 "code": "FLOW_NODE_1",
 "name": "环节A",
 "children": [{
  "id": 2,
  "code": "RULE_NODE_1",
  "name": "规则A"
 }, {
  "id": 3,
  "code": "RULE_NODE_2",
  "name": "规则B"
 }, {
  "id": 4,
  "code": "PARALLEL_NODE_2",
  "name": "并行节点",
  "children": [{
   "id": 5,
   "code": "RULE_NODE_3",
   "name": "规则C1"
  }, {
   "id": 6,
   "code": "RULE_COLLECTION_1",
   "name": "规则集1",
   "children": [{
    "id": 7,
    "code": "RULE_NODE_4",
    "name": "规则C21"
   }, {
    "id": 8,
    "code": "RULE_NODE_5",
    "name": "规则C22"
   }]
  }]
 }, {
  "id": 9,
  "code": "MUTUAL_NODE_1",
  "name": "互斥节点",
  "children": [{
   "id": 10,
   "code": "RULE_NODE_6",
   "name": "规则D1"
  }, {
   "id": 11,
   "code": "RULE_NODE_7",
   "name": "规则D2"
  }]
 }]
}, {
 "id": 12,
 "code": "FLOW_NODE_2",
 "name": "环节B"
}]

四、pom文件依赖

?
1
2
3
4
5
<dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>fastjson</artifactId>
     <version>1.2.49</version>
</dependency>

五、controller层

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package cn.chinaunicom.srigz.goods.admin.controller;
import cn.chinaunicom.srigz.goods.admin.service.CatagoryTreeService;
import cn.chinaunicom.srigz.goods.admin.utils.ActionHelper;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
public class CatagoryTreeController {
    @Autowired
    private CatagoryTreeService catagoryTreeService;
    @ApiOperation(value="查询分类树信息", notes="输入分类树Id")
    @RequestMapping(value = "/api/v1/tree_data/node/{treeId}", method = RequestMethod.GET)
    public Map getOne(@ApiParam(required = true, value = "分类树ID") @PathVariable Integer treeId){
        return ActionHelper.responseOk(catagoryTreeService.getOne(treeId));
    }
    @ApiOperation(value="新建节点", notes="根据输入参数创建节点")
    @RequestMapping(value = "/tree_data/node/{treeId}", method = RequestMethod.POST)
    public Map addOne(@ApiParam(required = true, value = "分类树ID")@PathVariable Integer treeId,
                      @ApiParam(required = true, value = "节点信息、父类ID、数组位置") @RequestBody Map map){
        return ActionHelper.responseOk(catagoryTreeService.addOne(treeId,map));
    }
    @ApiOperation(value="更新节点信息", notes="更新节点信息")
    @RequestMapping(value = "/tree_data/node/{treeId}/{id}", method = RequestMethod.PATCH)
    public Map updateOne(@ApiParam(required = true, value = "分类树ID")@PathVariable Integer treeId,
                         @ApiParam(required = true, value = "节点ID")@PathVariable Integer id,
                         @ApiParam(required = true, value = "节点信息") @RequestBody Map map){
        return ActionHelper.responseOk(catagoryTreeService.updateOne(treeId,id,map));
    }
    @ApiOperation(value="删除节点详情", notes="删除节点详情")
    @RequestMapping(method = RequestMethod.DELETE,value = "/tree_data/node/{treeId}/{id}")
    public Map remove(@ApiParam(required = true, value = "分类树ID")@PathVariable Integer treeId,
                      @ApiParam(required = true, value = "节点ID")@PathVariable Integer id){
        return ActionHelper.responseOk(catagoryTreeService.remove(treeId,id));
    }
}

六、service层

?
1
2
JSONArray jsonArray = JSON.parseArray(jsonTree); //由json字符串变成json数组对象
jsonArray.toJSONString() //由json数组对象变成json字符串
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package cn.chinaunicom.srigz.goods.admin.service;
import cn.chinaunicom.srigz.goods.admin.database.dao.CatagoryTreeRepository;
import cn.chinaunicom.srigz.goods.admin.database.model.CatagoryTree;
import cn.chinaunicom.srigz.goods.admin.utils.Recursive;
import cn.chinaunicom.srigz.goods.common.exception.AlreadyExistException;
import cn.chinaunicom.srigz.goods.common.exception.BadRequestException;
import cn.chinaunicom.srigz.goods.common.exception.NotFoundException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
@Service
public class CatagoryTreeService {
    @Autowired
    private CatagoryTreeRepository catagoryTreeRepository;
    /**
     * 查询单个分类树
     * @param treeId
     * @return
     */
    public JSON getOne(Integer treeId) {
        CatagoryTree catagoryTree = catagoryTreeRepository.findById(treeId.longValue()).get();
        return JSON.parseArray(catagoryTree.getJsonTree());
    }
    /**
     * 增加单个节点
     * @param treeId
     * @param map
     * @return
     */
    @Transactional
    public JSON addOne(Integer treeId, Map map) {
        CatagoryTree catagoryTree = catagoryTreeRepository.findById(treeId.longValue()).get();
        String jsonTree = catagoryTree.getJsonTree();
        JSONArray jsonArray = JSON.parseArray(jsonTree);
        Object parentId = map.get("parentId");
        Integer sequ = (Integer) map.get("sequ");
        if(sequ <= 0 ){
            throw new BadRequestException("数组位置不正确");
        }
        Map nodeMap = (Map) map.get("node");
        JSONObject node = new JSONObject(nodeMap);
        List list = new ArrayList();
        List keyList = Recursive.recursive(jsonArray,"id",list);
        for (Object key : keyList) {
            if (nodeMap.get("id").toString().equals(key.toString())) {
                throw new AlreadyExistException("节点ID为" + key);
            }
        }
        Recursive.addRecursive(jsonArray,node,sequ,"id",parentId);
        catagoryTree.setJsonTree(jsonArray.toJSONString());
        catagoryTreeRepository.save(catagoryTree);
        return jsonArray;
    }
    /**
     * 修改单个节点
     * @param treeId
     * @param id
     * @param map
     * @return
     */
    @Transactional
    public JSON updateOne(Integer treeId, Integer id, Map map) {
        CatagoryTree catagoryTree = catagoryTreeRepository.findById(treeId.longValue()).get();
        String jsonTree = catagoryTree.getJsonTree();
        JSONArray jsonArray = JSON.parseArray(jsonTree);
        List list = new ArrayList();
        List keyList = Recursive.recursive(jsonArray,"id",list);
        JSONObject node = new JSONObject(map);
        if (id.toString().equals(map.get("id").toString())) {
            for (Object key : keyList) {
                if (id.toString().equals(key.toString())) {
                    Recursive.updateRecursive(jsonArray,"id",id,node);
                    catagoryTree.setJsonTree(jsonArray.toJSONString());
                    catagoryTree.setModifyTime(new Date());
                    catagoryTreeRepository.save(catagoryTree);
                    return jsonArray;
                }
            }
        }else {
            throw new BadRequestException("id is not allowed to be modified");
        }
        throw new NotFoundException("节点ID为" + id);
    }
    /**
     * 删除节点以及子节点
     * @param treeId
     * @param id
     * @return
     */
    @Transactional
    public JSON remove(Integer treeId, Integer id) {
        CatagoryTree catagoryTree = catagoryTreeRepository.findById(treeId.longValue()).get();
        String jsonTree = catagoryTree.getJsonTree();
        JSONArray jsonArray = JSON.parseArray(jsonTree);
        List list = new ArrayList();
        List keyList = Recursive.recursive(jsonArray,"id",list);
        for (Object key : keyList) {
            if (id.toString().equals(key.toString())) {
                Recursive.removeRecursive(jsonArray,"id",id);
                catagoryTree.setJsonTree(jsonArray.toJSONString());
                catagoryTreeRepository.save(catagoryTree);
                return jsonArray;
            }
        }
        throw new NotFoundException("节点ID为" + id);
    }
}

七、把增删查改的递归方法写成工具类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package cn.chinaunicom.srigz.goods.admin.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.List;
public class Recursive {
    /**
     * 递归取出所有Key对应的value值
     * @param jsonArray     需要查询的目标主体
     * @param key           需要查询的字段名key
     * @param list          存储value值
     * @return
     */
    public static List recursive(JSONArray jsonArray, String key, List list) {
        for (Object obj : jsonArray) {
            JSONObject jsonObject = (JSONObject) obj;
            JSONArray children = jsonObject.getJSONArray("children");
            if (children != null) {
                list.add(jsonObject.get(key));
                recursive(children,key,list);
            }else {
                list.add(jsonObject.get(key));
            }
        }
        return list;
    }
    /**
     * 增加节点
     * @param jsonArray     需要更新的目标主体
     * @param node          增加节点信息
     * @param sequ          数组的位置
     * @param key           目标主体中的字段名key
     * @param value         节点信息与key对应的value
     */
    public static void addRecursive(JSONArray jsonArray, JSONObject node, Integer sequ, String key, Object value) {
        for (Object obj : jsonArray) {
            JSONObject jsonObject = (JSONObject) obj;
            JSONArray children = jsonObject.getJSONArray("children");
            if (children != null) {
                if (value.toString().equals(jsonObject.get(key).toString())) {
                    if(sequ > children.size()){
                        children.add(children.size(), node);
                    }else{
                        children.add(sequ-1, node);
                    }
                    return;
                }
                addRecursive(children,node,sequ,key,value);
            } else {
                if (value.toString().equals(jsonObject.get(key).toString())) {
                    JSONArray array = new JSONArray();
                    array.add(node);
                    jsonObject.put("children", array);
                    return;
                }
            }
        }
    }
    /**
     * 根据条件更新节点
     * @param jsonArray 需要更新的目标主体
     * @param key       目标主体中的字段名key
     * @param value     更新节点信息与key对应的value
     * @param node      更新节点信息
     */
    public static void updateRecursive(JSONArray jsonArray, String key, Object value, JSONObject node) {
        for (int i = 0; i < jsonArray.size() ; i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            JSONArray children = jsonObject.getJSONArray("children");
            if (value.toString().equals(jsonObject.get(key).toString())) {
                if(children != null){
                    node.put("children",children);
                }
                jsonArray.set(i,node);
                return;
            }else if(children != null){
                updateRecursive(children,key,value,node);
            }
        }
    }
    /**
     * 删除节点
     * @param jsonArray     需要更新的目标主体
     * @param key           目标主体中的字段名key
     * @param value         节点信息与key对应的value
     */
    public static void removeRecursive(JSONArray jsonArray,String key,Object value) {
        for (Object obj : jsonArray) {
            JSONObject jsonObject = (JSONObject) obj;
            if (value.toString().equals(jsonObject.get(key).toString())) {
                jsonArray.remove(jsonObject);
                return;
            }
            JSONArray children = jsonObject.getJSONArray("children");
            if (children != null) {
                removeRecursive(children,key,value);
            }
        }
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/zhangrui1037102215/article/details/80619398

延伸 · 阅读

精彩推荐