欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-29 08:00:01
json字符串插入节点或者覆盖节点jfdajson是json字符串jsonobject obj=jsonobject.parseobject(jfdajson);obj.put("dj",xydjdm...

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

jfdajson是json字符串

jsonobject obj=jsonobject.parseobject(jfdajson);
obj.put("dj",xydjdm);// 更新dj字段
obj.put("xydjmc",xydjmc);// 添加xydjmc字段
obj.tostring();

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

一、功能实现

1、节点树查询:

按id查询树

2、节点新增:

http://host/tree_data/node/${treeid}
in: {node: {key: ..., ...}, parent: ${key}, sequ: ${sequ}}

3、节点修改

http://host/tree_data/node/${treeid}/${key}
in: {node: {key: ..., ...}}

4、节点删除

http://host/tree_data/node/${treeid}/${key}

二、数据表结构

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

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字符串

[{
 "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文件依赖

<dependency>
     <groupid>com.alibaba</groupid>
     <artifactid>fastjson</artifactid>
     <version>1.2.49</version>
</dependency>

五、controller层

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层

jsonarray jsonarray = json.parsearray(jsontree); //由json字符串变成json数组对象
jsonarray.tojsonstring() //由json数组对象变成json字符串
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);
    }
}

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

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);
            }
        }
    }
}

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