You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于JSONPath修改指定JSON节点键值的Java实现问询

完善Java代码实现JSON路径指定键值修改

Got it, let's polish your code to successfully modify the target JSON value using the given dot-separated path. Here's the complete implementation with clear explanations:

完整代码实现

import org.json.JSONObject;
import org.json.JSONParser;
import org.json.ParseException;
import com.jayway.jsonpath.JsonPath;
import org.junit.Assert;

public class JsonModifier {

    public String setProperty(String fileString, String path, String value) {
        // 先验证目标路径是否存在
        if (JsonPath.given(fileString).get(path) == null) {
            Assert.fail("Path does not exist on json file");
            return fileString; // 路径不存在时返回原始字符串
        }

        try {
            JSONParser jsonParser = new JSONParser();
            JSONObject jsonObject = (JSONObject) jsonParser.parse(fileString);
            String[] tokens = path.split("\\.");
            
            // 逐层遍历到目标键的父节点
            JSONObject currentObj = jsonObject;
            for (int i = 0; i < tokens.length - 1; i++) {
                String token = tokens[i];
                // 确保当前层级的节点存在且是JSONObject类型
                if (!currentObj.has(token) || !(currentObj.get(token) instanceof JSONObject)) {
                    Assert.fail("Invalid path segment: " + token);
                    return fileString;
                }
                currentObj = (JSONObject) currentObj.get(token);
            }
            
            // 修改最后一个键对应的目标值
            String targetKey = tokens[tokens.length - 1];
            currentObj.put(targetKey, value);
            
            // 返回格式化后的修改结果(带缩进更易读)
            return jsonObject.toString(4);
        } catch (ParseException ex) {
            ex.printStackTrace();
            return fileString;
        } catch (NullPointerException ex) {
            ex.printStackTrace();
            return fileString;
        }
    }

    // 测试示例
    public static void main(String[] args) {
        String originalJson = "{ \"contract\": { \"marketScope\": \"AT\", \"businessPartner\": \"GBM\", \"salesChannelInformation\": { \"salesChannelCode\": \"Integrated\", \"salesChannel\": \"B-Partner information 1\" } } }";
        JsonModifier modifier = new JsonModifier();
        String modifiedJson = modifier.setProperty(originalJson, "contract.salesChannelInformation.salesChannelCode", "Integrated-Test");
        System.out.println("修改后的JSON:\n" + modifiedJson);
    }
}

关键逻辑说明

  • 路径有效性校验:先用JsonPath确认目标路径存在,避免对无效路径做操作
  • 层级定位:循环遍历路径的前n-1个节点,精准定位到目标键的父级JSONObject
  • 值更新:通过put方法直接覆盖目标键的原有值,org.json库原生支持这种操作
  • 健壮性保障:保留异常捕获逻辑,出错时返回原始JSON字符串,避免程序崩溃

测试输出

运行main方法后,会输出格式化后的修改结果:

{
    "contract": {
        "marketScope": "AT",
        "businessPartner": "GBM",
        "salesChannelInformation": {
            "salesChannelCode": "Integrated-Test",
            "salesChannel": "B-Partner information 1"
        }
    }
}

内容的提问来源于stack exchange,提问作者Luis Urea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:58:57