首页
学习
活动
专区
工具
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对象。你可以根据需要对其进行进一步处理或获取其属性值。

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

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

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

相关·内容

57秒

Jquery如何获取和设置元素内容?

5分12秒

python开发视频课程5.12如何获取指定元素出现的次数

24分55秒

108.尚硅谷_JS基础_获取元素的样式

6分49秒

08-如何获取插件的帮助信息

6分40秒

14,如何高效率判断集合的元素是否唯一?

1分40秒

如何获取苹果设备的UDID(iPhoneiPad UDID查询方法)

1分40秒

如何获取苹果设备的UDID(iPhone/iPad UDID查询方法)

10分33秒

如何在网页置灰的时候,部分元素保持彩色-有意思的面试题

10分38秒

06_尚硅谷_谷粒音乐_如何获取三个视口的宽度.wmv

6分27秒

083.slices库删除元素Delete

7分21秒

6-云托管下用户信息获取及token应用

7分19秒

085.go的map的基本使用

领券