记录Java递归遍历json对象,修改指定key的value值

一、前言

最近在项目中遇到的需求,需要对JSON数据进行修改存储

1、根据节点,修改指定key的value值

2、修改json中指定key的value值

3、根据json节点获取value值

4、根据字段名获取value值

使用alibaba的Fastjson包


    com.alibaba
    fastjson
    1.2.83

二、实现代码

package com.fortunes.javamg.modules.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @version V1.0
 * @Description:JSON工具类
 */
public class JsonUtils {

    /**数据更新标识*/
    public static boolean flag = false;

    /****
     * @Description :根据json字段名称查找对应值
     * @param json
     * @param param
     * @return java.lang.String
     */
    public static String getJsonParam(String json, String param) {
        String regex = param + "\":(.*?)(,|})";//
        Matcher matcher = Pattern.compile(regex).matcher(json);
        String returnStr = null;
        while (matcher.find()) {
            String ret = matcher.group(1);
            returnStr = ret;
        }
        if (returnStr == null) {
            return null;
        } else {
            return returnStr.replaceAll("\"", "").replaceAll("}", "").replaceAll("]", "");
        }

    }

    /***
     * @Description :自定义获取节点数据
     * @param objJson
     * @param node
     * @return java.lang.Object
     */
    public static Object getNodeJson(Object objJson, String node) {
        if (objJson instanceof JSONArray) {
            JSONArray objArray = (JSONArray) objJson;
            for (int i = 0; i < objArray.size(); i++) {
                getNodeJson(objArray.get(i), node);
            }
        } else if (objJson instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) objJson;
            Iterator it = jsonObject.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next().toString();
                Object object = jsonObject.get(key);
                if (key.equals(node)) {
                    objJson = object;
                    break;
                }
                if (object instanceof JSONArray) {
                    JSONArray objArray = (JSONArray) object;
                    getNodeJson(objArray, node);
                } else if (object instanceof JSONObject) {
                    getNodeJson(object, node);
                }
            }
        }
        return objJson;
    }

    /***
     * @Description :更新JSON数据
     * @param objJson
     * @param nodeKey
     * @param nodeValue
     * @return java.lang.Object
     */
    public static Object updateJson(Object objJson, String nodeKey, String nodeValue) {
        //如果obj为json数组
        if (objJson instanceof JSONArray) {
            JSONArray objArray = (JSONArray) objJson;
            for (int i = 0; i < objArray.size(); i++) {
                updateJson(objArray.get(i), nodeKey, nodeValue);
            }
        } else if (objJson instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) objJson;
            Iterator it = jsonObject.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next().toString();
                Object object = jsonObject.get(key);
                if (object instanceof JSONArray) {
                    JSONArray objArray = (JSONArray) object;
                    updateJson(objArray, nodeKey, nodeValue);
                } else if (object instanceof JSONObject) {
                    updateJson(object, nodeKey, nodeValue);
                } else {
                    if (key.equals(nodeKey)) {
                        //替换数据
                        jsonObject.put(key, nodeValue);
                    }
                }
            }
        }
        return objJson;
    }

    /***
     * @Description :更新节点下的JSON数据
     * @param objJson
     * @param node
     * @param nodeKey
     * @param nodeValue
     * @return java.lang.Object
     */
    public static Object updateNodeJson(Object objJson, String node, String nodeKey, String nodeValue) {
        //如果obj为json数组
        if (objJson instanceof JSONArray) {
            JSONArray objArray = (JSONArray) objJson;
            for (int i = 0; i < objArray.size(); i++) {
                updateNodeJson(objArray.get(i), node, nodeKey, nodeValue);
            }
        } else if (objJson instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) objJson;
            Iterator it = jsonObject.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next().toString();
                Object object = jsonObject.get(key);
                //判断key是否相等
                if (key.equals(node)) {
                    //修改对应的字段
                    setJsonValue(object, nodeKey, nodeValue);
                    flag = true;
                    break;
                } else {
                    if (object instanceof JSONArray) {
                        JSONArray objArray = (JSONArray) object;
                        updateNodeJson(objArray, node, nodeKey, nodeValue);
                    } else if (object instanceof JSONObject) {
                        updateNodeJson(object, node, nodeKey, nodeValue);
                    }
                }
            }
        }
        return objJson;
    }

    /***
     * @Description :修改对应的字段
     * @param obj
     * @param key
     * @param value
     * @return void
     */
    public static void setJsonValue(Object obj, String key, String value) {
        if (obj instanceof JSONArray) {
            JSONArray arr = (JSONArray) obj;
            for (int i = 0; i < arr.size(); i++) {
                JSONObject jsonObject = arr.getJSONObject(i);
                if (StringUtils.isNotEmpty(jsonObject.getString(key))) {
                    //替换数据
                    jsonObject.put(key, value);
                }
            }
        } else {
            JSONObject jsonObject = (JSONObject) obj;
            if (StringUtils.isNotEmpty(jsonObject.getString(key))) {
                //替换数据
                jsonObject.put(key, value);
            }
        }
    }
}

三、测试代码

public static void main(String[] args) throws Exception{
        String json="{\"unitDTO\":{\"name\":\"顺德门诊部\",\"unitNumber\":10007},\"loginId\":\"sddella\",\"previewflag\":\"0\",\"busiStage\":\"\",\"isOnline\":\"1\",\"personBaseInfoDTO\":{\"transferAccountType\":\"1\",\"householdAddress\":\"广东省未知\",\"migrantFlag\":\"0\"},\"busiState\":\"1\",\"riskViewParams\":\"[{\\\"aac001\\\":123456}]\",\"officeDTO\":{\"contactNoteNumber\":\"441284JY031\",\"tgtAgencyState\":\"440606\",\"householdAddress\":\"广东省未知\",\"changeDate\":20220211,\"srcAgencyState\":\"441284\",\"newInsurance\":\"120\",\"sysTraceId\":\"10332134\",\"sex\":\"1\"},\"settleDTO\":{\"insurance\":\"110\",\"remark\":\"\",\"transDirection\":\"0\",\"changeDate\":20220211,\"transRegion\":\"1\",\"unitName\":\"顺德门诊部\",\"transWay\":\"1\"},\"officeList\":[{\"remark\":\"\",\"contactPhone\":\"1234\"},{\"remark\":\"\",\"contactPhone\":\"1234\"}]}";
        JSONObject val = JSONObject.parseObject(json);
        String node="unitDTO";
        //判断节点是否存在
        if (!val.containsKey(node)){
            System.out.println("节点数据为空");
            return;
        }
        System.out.println("=============根据节点修改数据=============");
        System.out.println("更新前数据:" + val);
        Object obj = JsonUtils.updateNodeJson(val, node, "name", "123456");
        System.out.println("数据更新成功:"+JsonUtils.flag);
        System.out.println("更新后数据:" + obj);
        System.out.println("=============根据节点获取数据=============");
        Object nodeJson = JsonUtils.getNodeJson(val, node);
        System.out.println("节点数据:" + nodeJson);
        System.out.println("============根据字段名获取数据============");
        String contactNoteNumber = JsonUtils.getJsonParam(json, "contactNoteNumber");
        System.out.println("字段数据:" + contactNoteNumber);
        System.out.println("==========修改数据中所有匹配的key==========");
        Object updateJson=JsonUtils.updateJson(val,"householdAddress","广东省深圳市");
        System.out.println("更新后数据:" + updateJson);
    }

四、效果如下

记录Java递归遍历json对象,修改指定key的value值_第1张图片

 

你可能感兴趣的:(Java,java,json)