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

如何在Java中解析未知内容结构的JSON文件

如何解析未知结构的JSON文件

当你不知道JSON文件的具体字段时,核心思路是遍历所有键值对,并根据值的类型(字符串、数字、数组、嵌套对象)做递归处理。下面针对几种常用语言给出具体实现:

Java(以org.json库为例)

如果你用的是org.json.JSONObject,可以通过keySet()获取所有字段名,再逐个判断值的类型,递归处理嵌套结构:

import org.json.JSONObject;
import org.json.JSONArray;
import java.io.FileReader;

public class UnknownJsonParser {
    public static void main(String[] args) throws Exception {
        // 从文件加载JSON对象
        JSONObject rootObj = new JSONObject(new FileReader("your/json/file/path.json"));
        
        // 遍历根节点的所有字段
        iterateJson(rootObj, 0);
    }

    private static void iterateJson(Object jsonObj, int indentLevel) {
        String indent = "  ".repeat(indentLevel);
        
        if (jsonObj instanceof JSONObject obj) {
            for (String key : obj.keySet()) {
                Object value = obj.get(key);
                System.out.printf("%sKey: %s%n", indent, key);
                // 递归处理值
                iterateJson(value, indentLevel + 1);
            }
        } else if (jsonObj instanceof JSONArray array) {
            for (int i = 0; i < array.length(); i++) {
                Object element = array.get(i);
                System.out.printf("%sArray index %d:%n", indent, i);
                iterateJson(element, indentLevel + 1);
            }
        } else {
            // 基础类型(字符串、数字、布尔、null)
            System.out.printf("%sValue: %s%n", indent, jsonObj);
        }
    }
}

Python

Python的json模块会把JSON解析成字典或列表,直接遍历即可,递归处理嵌套结构非常直观:

import json

def iterate_json(json_data, indent_level=0):
    indent = "  " * indent_level
    
    if isinstance(json_data, dict):
        for key, value in json_data.items():
            print(f"{indent}Key: {key}")
            iterate_json(value, indent_level + 1)
    elif isinstance(json_data, list):
        for idx, item in enumerate(json_data):
            print(f"{indent}Array index {idx}:")
            iterate_json(item, indent_level + 1)
    else:
        print(f"{indent}Value: {json_data}")

# 加载并解析JSON文件
with open("your/json/file/path.json", "r", encoding="utf-8") as f:
    data = json.load(f)
    iterate_json(data)

实用小技巧

  1. 先快速查看结构:如果只是想先了解JSON的大致结构,不用写代码,直接用命令行工具jq(大部分系统可安装),执行jq . your-file.json就能格式化输出整个JSON,清晰看到所有字段和嵌套关系。
  2. 处理超大JSON:如果JSON文件特别大(几十MB以上),避免一次性加载整个文件到内存,用流式解析:
    • Java用javax.json.JsonParser做流式读取
    • Python用ijson库,按事件流逐个解析节点

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 01:52:33