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

Java中如何将以JSONPath为键的JSONObject转为嵌套JSON?

将JSONPath键的JSONObject转换为嵌套JSON结构

手动实现方案

核心逻辑是解析JSONPath的每个节点片段,逐步构建嵌套的对象和数组结构,区分对象属性与数组索引两种场景:

  1. 拆分JSONPath:移除开头的$符号,按.和[]分割路径片段(比如$.user[0].name拆分为user、0、name)。
  2. 遍历构建结构:从根对象开始,逐个处理片段:
    • 若片段是数组索引(如[0]),则确保当前父节点是数组,长度不足时填充空对象,再定位到对应索引的元素。
    • 若片段是对象属性,则确保当前父节点是对象,不存在该属性时创建空对象,再定位到子节点。
  3. 设置最终值:遍历完所有片段后,将对应值赋值到最终节点。

基于org.json的代码示例

import org.json.JSONArray;
import org.json.JSONObject;

public class JsonPathConverter {
    public static JSONObject convert(JSONObject jsonPathMap) {
        JSONObject root = new JSONObject();
        for (String path : jsonPathMap.keySet()) {
            Object value = jsonPathMap.get(path);
            // 移除路径开头的$符号
            String cleanPath = path.replaceFirst("^\\$", "");
            // 分割路径片段,处理[]和.的边界
            String[] segments = cleanPath.split("(?=\\[)|(?<=\\])|\\.");
            
            Object currentNode = root;
            for (int i = 0; i < segments.length; i++) {
                String segment = segments[i].trim();
                if (segment.isEmpty()) continue;

                // 处理数组索引片段,例如[0]
                if (segment.startsWith("[") && segment.endsWith("]")) {
                    int index = Integer.parseInt(segment.substring(1, segment.length() - 1));
                    JSONArray targetArray;

                    if (currentNode instanceof JSONObject) {
                        // 父节点是对象,先获取或创建对应数组属性
                        String parentKey = segments[i-1].trim();
                        targetArray = ((JSONObject) currentNode).optJSONArray(parentKey);
                        if (targetArray == null) {
                            targetArray = new JSONArray();
                            ((JSONObject) currentNode).put(parentKey, targetArray);
                        }
                    } else {
                        targetArray = (JSONArray) currentNode;
                    }

                    // 确保数组长度足够,不足则填充空对象
                    while (targetArray.length() <= index) {
                        targetArray.put(new JSONObject());
                    }
                    currentNode = targetArray.get(index);
                } else if (i < segments.length - 1) {
                    // 处理对象属性(非最后一个片段)
                    if (currentNode instanceof JSONObject) {
                        JSONObject childNode = ((JSONObject) currentNode).optJSONObject(segment);
                        if (childNode == null) {
                            childNode = new JSONObject();
                            ((JSONObject) currentNode).put(segment, childNode);
                        }
                        currentNode = childNode;
                    }
                } else {
                    // 最后一个片段,设置目标值
                    if (currentNode instanceof JSONObject) {
                        ((JSONObject) currentNode).put(segment, value);
                    }
                }
            }
        }
        return root;
    }

    public static void main(String[] args) {
        JSONObject input = new JSONObject();
        input.put("$.user[0].name", "Alice");
        input.put("$.user[0].age", 25);
        input.put("$.user[1].name", "Bob");
        input.put("$.settings.theme", "dark");
        
        JSONObject output = convert(input);
        System.out.println(output.toString(2));
    }
}

推荐Java库

如果不想手动实现,这些库可以快速解决问题:

  • Jayway JsonPath:虽然主打JSONPath查询,但支持通过set方法直接在空JSON上逐步构建嵌套结构,循环处理所有键值对即可。
    import com.jayway.jsonpath.JsonPath;
    
    public class JsonPathLibConverter {
        public static String convert(JSONObject jsonPathMap) {
            String json = "{}";
            for (String path : jsonPathMap.keySet()) {
                json = JsonPath.parse(json).set(path, jsonPathMap.get(path)).jsonString();
            }
            return json;
        }
    }
    
  • Jackson Databind:可以将JSONPath对应的键值对映射到嵌套POJO,再序列化为标准JSON。适合已经定义了数据模型的场景。
  • Apache Commons Configuration:JSONConfiguration类支持从类似JSONPath的键加载配置,也能反向生成嵌套JSON结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 18:30:58