优雅的遍历JSONArray,获取里面的数据

最近看到有个同事在遍历json数组的时候,用for循环写了一层有一层,那么是否有简便的写法呢?当然有了,下面就有用流的行驶,优雅的遍历数组,获取我们想要的数据

bash 复制代码
public static void main(String[] args) {
    String structure = "[{\"key\":\"111\",\"isRequired\":true,\"isNumber\":true,\"isFixed\":true},{\"key\":\"2\",\"isFixed\":true},{\"key\":\"3\",\"isNumber\":true},{\"key\":\"4\",\"isRequired\":true}]";
    JSONArray jsonArray;

    try {
        jsonArray = JSON.parseArray(structure);
    } catch (JSONException e) {
        System.err.println("Invalid JSON format: " + e.getMessage());
        return;
    }

    List<String> unitList = Optional.ofNullable(jsonArray)
            .orElse(new JSONArray())
            .stream()
            .filter(item -> item instanceof JSONObject)
            .map(item -> {
                JSONObject jsonObject = (JSONObject) item;
                String key = jsonObject.getString("key");
                return key;
            })
            .collect(Collectors.toList());

    System.out.println(unitList);
}
相关推荐
程序无bug14 分钟前
手写Spring框架
java·后端
程序无bug16 分钟前
Spring 面向切面编程AOP 详细讲解
java·前端
全干engineer28 分钟前
Spring Boot 实现主表+明细表 Excel 导出(EasyPOI 实战)
java·spring boot·后端·excel·easypoi·excel导出
Fireworkitte37 分钟前
Java 中导出包含多个 Sheet 的 Excel 文件
java·开发语言·excel
GodKeyNet1 小时前
设计模式-责任链模式
java·设计模式·责任链模式
a_Dragon11 小时前
Spring Boot多环境开发-Profiles
java·spring boot·后端·intellij-idea
泽02021 小时前
C++之红黑树认识与实现
java·c++·rpc
ChinaRainbowSea1 小时前
补充:问题:CORS ,前后端访问跨域问题
java·spring boot·后端·spring
KiddoStone2 小时前
多实例schedule job同步数据流的数据一致性设计和实现方案
java
岁忧2 小时前
(LeetCode 每日一题) 1865. 找出和为指定值的下标对 (哈希表)
java·c++·算法·leetcode·go·散列表