优雅的遍历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);
}
相关推荐
莫问前路漫漫3 分钟前
Java Runtime Environment(JRE)全解析:Java 程序跨平台运行的核心基石
java·开发语言
进阶小白猿5 分钟前
Java技术八股学习Day22
java·开发语言·学习
蒟蒻的贤9 分钟前
操作系统复习
java·开发语言·数据库
sanggou20 分钟前
Spring Boot 中基于 WebClient 的 SSE 流式接口实战
java·人工智能
未若君雅裁21 分钟前
SpringBoot2.x与SpringBoot3.x自动配置注册的差异
java·spring boot
AI视觉网奇26 分钟前
ue 5.5 c++ mqtt 订阅/发布 json
网络·c++·json
赵八斤27 分钟前
java 项目中配置多个数据源
java·开发语言·数据库
小冷coding32 分钟前
【Java】以 Java + Redis + MySQL 为技术栈,模拟电商商品详情的读写场景,Cache Aside+ 延迟双删 方案
java·redis·mysql
SuperherRo37 分钟前
JAVA攻防-Ys项目Gadget链分析&CC2&CC4&CC5&CC7&入口点改动&触发点改动
java·cc2·cc4·cc5·cc7·gadget链
2501_9445264238 分钟前
Flutter for OpenHarmony 万能游戏库App实战 - 关于页面实现
android·java·开发语言·javascript·python·flutter·游戏