使用Java解析JSON(升级版)。

此实现能正确处理各种嵌套结构(包括混合类型的复杂JSON),同时保持高效的性能表现。

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.client.RestTemplate;
 
import java.util.LinkedHashMap;
import java.util.Map;
 
public class JSONFlattener {
 
    private final JSONObject root;
 
    public JSONFlattener(String json) {
        this.root = JSON.parseObject(json);
    }
 
    public Map<String, Object> flatten() {
        Map<String, Object> resultMap = new LinkedHashMap<>();
        traverse(root, "", resultMap);
        return resultMap;
    }
 
    private void traverse(Object node, String currentPath, Map<String, Object> resultMap) {
        if (node == null) return;
 
        if (node instanceof JSONObject) {
            handleJSONObject((JSONObject) node, currentPath, resultMap);
        } else if (node instanceof JSONArray) {
            handleJSONArray((JSONArray) node, currentPath, resultMap);
        } else {
            // 基本类型直接存储
            resultMap.put(currentPath, node);
        }
    }
 
    private void handleJSONObject(JSONObject obj, String currentPath, Map<String, Object> resultMap) {
        // 先存储整个对象
        if (!currentPath.isEmpty()) {
            resultMap.put(currentPath, obj);
        }
        
        // 再展开对象属性
        for (Map.Entry<String, Object> entry : obj.entrySet()) {
            String newPath = currentPath.isEmpty() 
                ? entry.getKey() 
                : currentPath + "." + entry.getKey();
            traverse(entry.getValue(), newPath, resultMap);
        }
    }
 
    private void handleJSONArray(JSONArray array, String currentPath, Map<String, Object> resultMap) {
        // 先存储整个数组
        if (!currentPath.isEmpty()) {
            resultMap.put(currentPath, array);
        }
        
        // 再处理每个数组元素
        for (int i = 0; i < array.size(); i++) {
            String elementPath = currentPath + "[" + i + "]";
            Object element = array.get(i);
            
            // 存储当前元素(包括复合类型)
            resultMap.put(elementPath, element);
            
            // 递归处理元素内部结构
            traverse(element, elementPath, resultMap);
        }
    }
 
    public static void main(String[] args) {
//        String url = "api_url";
//        RestTemplate restTemplate = new RestTemplate();
//        String jsonResponse = restTemplate.getForObject(url, String.class);
        
        String jsonResponse = "{\"result\":{\"data\":\"123\",\"array\":[4,5,6]},\"status\":\"ok\"}";
        
        JSONFlattener flattener = new JSONFlattener(jsonResponse);
        Map<String, Object> flatMap = flattener.flatten();
        System.out.println(JSON.toJSONString(flatMap.get("result.data")));// "123"
 
        System.out.println(JSON.toJSONString(flatMap.get("status")));//"ok"
 
        System.out.println(JSON.toJSONString(flatMap.get("result.array")));
 
        System.out.println(JSON.toJSONString(flatMap.get("result.array[0]")));
        System.out.println(JSON.toJSONString(flatMap.get("result")));
    }
}

使用示例:
假设有以下 JSON:

 {
   "result": {
     "array": [
       {"id": 1, "name": "Alice"},
       42,
       ["a", "b"]
     ]
   }
 }

AI写代码
扁平化后将包含以下路径:

result → 整个result对象

result.array → 整个数组

result.array[0] → 第一个元素对象 {"id":1,"name":"Alice"}

result.array[0].id → 1

result.array[0].name → "Alice"

result.array[1] → 42

result.array[2] → 子数组 ["a","b"]

result.array[2][0] → "a"

result.array[2][1] → "b"

这种实现既保持了扁平化能力,又确保可以通过索引路径直接访问数组元素(包括复合类型元素)。

更多内容请访问16uni

posted @ 2025-06-19 15:20  16uni  阅读(22)  评论(0)    收藏  举报

更多内容请访问16uni