首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何获取JSONArray的最深层元素

获取JSONArray的最深层元素可以通过递归的方式来实现。下面是一个示例代码:

代码语言:txt
复制
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Main {
    public static void main(String[] args) {
        String jsonString = "[{\"name\":\"John\",\"age\":30,\"city\":\"New York\"},[1,2,3,[4,5,6,[7,8,9]]],{\"key\":\"value\"}]";
        try {
            JSONArray jsonArray = new JSONArray(jsonString);
            JSONObject deepestElement = getDeepestElement(jsonArray);
            System.out.println("最深层元素:" + deepestElement.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public static JSONObject getDeepestElement(JSONArray jsonArray) throws JSONException {
        JSONObject deepestElement = null;
        int maxDepth = -1;

        for (int i = 0; i < jsonArray.length(); i++) {
            Object element = jsonArray.get(i);
            if (element instanceof JSONArray) {
                JSONObject subElement = getDeepestElement((JSONArray) element);
                int depth = getDepth(subElement);
                if (depth > maxDepth) {
                    maxDepth = depth;
                    deepestElement = subElement;
                }
            } else if (element instanceof JSONObject) {
                int depth = getDepth((JSONObject) element);
                if (depth > maxDepth) {
                    maxDepth = depth;
                    deepestElement = (JSONObject) element;
                }
            }
        }

        return deepestElement;
    }

    public static int getDepth(JSONObject jsonObject) {
        int maxDepth = 0;

        String[] keys = JSONObject.getNames(jsonObject);
        if (keys != null) {
            for (String key : keys) {
                Object value = jsonObject.get(key);
                if (value instanceof JSONObject) {
                    int depth = getDepth((JSONObject) value) + 1;
                    if (depth > maxDepth) {
                        maxDepth = depth;
                    }
                }
            }
        }

        return maxDepth;
    }
}

这段代码首先定义了一个JSON字符串,然后通过JSONArray和JSONObject类来解析JSON字符串。getDeepestElement方法使用递归的方式遍历JSONArray中的元素,如果遇到嵌套的JSONArray或JSONObject,则继续递归调用getDeepestElement方法。getDepth方法用于计算JSONObject的深度。

该代码的输出结果是最深层元素的JSONObject对象。你可以根据需要对其进行进一步处理或获取其属性值。

腾讯云相关产品和产品介绍链接地址:

请注意,以上仅为示例产品,腾讯云还提供更多丰富的云计算产品和服务,可根据具体需求选择合适的产品。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券