Java 小抄|解析 JSON 并提取特定层级数据

文章目录

前言

在日常开发中,我们经常需要从 JSON 数据中提取特定的信息。本文将介绍如何使用 Java 和 Gson 库解析 JSON 数据,并通过流式处理提取特定层级的数据。我们将以一个具体的例子来说明这一过程。

环境准备

依赖库

本文使用了以下依赖库:

  • Gson: 用于 JSON 解析。
  • Lombok: 用于简化 Java 类的编写。

在 pom.xml 文件中添加以下依赖:

xml 复制代码
<dependencies>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.8</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.20</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

示例代码

JSON 数据

假设我们有以下 JSON 数据,表示多个预算条目及其子条目:

json 复制代码
[
    {
        "id": 1309,
        "code": "BD000020",
        "level": 1,
        "children": [
            {
                "id": 1664,
                "code": "BD000020001",
                "level": 2,
                "children": [
                    {
                        "id": 1665,
                        "code": "BD000020001001",
                        "level": 3
                    }
                ]
            }
        ]
    },
    {
        "id": 1226,
        "code": "BD000014",
        "level": 1,
        "children": [
            {
                "id": 1227,
                "code": "BD000014001",
                "level": 2,
                "children": [
                    {
                        "id": 1229,
                        "code": "BD000014001001",
                        "level": 3
                    }
                ]
            },
            {
                "id": 1228,
                "code": "BD000014002",
                "level": 2,
                "children": [
                    {
                        "id": 1230,
                        "code": "BD000014002001",
                        "level": 3
                    }
                ]
            }
        ]
    }
]

Java 类定义

首先,我们需要定义一个 Java 类来表示预算条目。这里使用 Lombok 的 @Data 注解来简化类的编写。

java 复制代码
import lombok.Data;

@Data
class Budget {
    private String code;
    private Integer level;
    private List<Budget> children;
}

解析 JSON 数据

接下来,我们使用 Gson 库将 JSON 字符串解析为 List<Budget> 对象。

java 复制代码
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.List;

public class Level {
    private static String json = "[...]" // 上述 JSON 数据

    public static void main(String[] args) {
        // 将 jsonString 转成 List<Budget> 对象
        Gson gson = new Gson();
        List<Budget> budgets = gson.fromJson(json, new TypeToken<List<Budget>>() {}.getType());
        System.out.println(budgets);

        // 通过 stream 获取 budget 中所有 level=3 的 code
        List<String> codes = budgets.stream()
                .flatMap(budget -> getCodesWithLevelThree(budget))
                .collect(Collectors.toList());
        System.out.println(codes);
    }

    private static Stream<String> getCodesWithLevelThree(Budget budget) {
        if (budget.getLevel() == 3) {
            return Stream.of(budget.getCode());
        } else if (budget.getChildren() != null) {
            return budget.getChildren().stream().flatMap(Level::getCodesWithLevelThree);
        }
        return Stream.empty();
    }
}

代码解释

  1. 解析 JSON 数据:

    • 使用 Gson 库将 JSON 字符串解析为 List<Budget> 对象。
    • TypeToken 用于指定泛型类型。
  2. 提取特定层级的数据:

    • 使用 Stream API 递归地遍历每个预算条目及其子条目。
    • getCodesWithLevelThree 方法检查当前条目的层级是否为 3,如果是,则返回其代码;否则,递归处理其子条目。
  3. 输出结果:

    • 打印解析后的 List<Budget> 对象。
    • 打印所有层级为 3 的代码。

结论

通过本文的示例,我们可以看到使用 Java 和 Gson 库解析 JSON 数据并提取特定层级的数据是非常简单和高效的。希望本文能对大家在实际开发中处理类似问题提供帮助。

相关推荐
aiotto资源分享13 分钟前
Python 写 JSON 文件,程序中途退出会留下什么?
java·python·json·jsondecodeerror
RuoyiOffice1 小时前
SpringBoot3+Vue3 采购到付款:ERP、WMS与财务如何按同一来源协同
java·spring boot·架构·vue
文丑颜不良啊1 小时前
LeetCode3261~3280题目解析
java·leetcode
代码不停1 小时前
Spring 原理
java·spring
企业数字化笔记2 小时前
报表上线怎么对账?口径回归、权限抽检与差异定位
java·spring boot·mysql
乌暮2 小时前
少写重复 CRUD:用大白话搞懂 MyBatis-Plus
java·开发语言·spring boot·面试·mybatis
CoderYanger2 小时前
Java EE 进阶:9.MyBatis 操作数据库(进阶)(第四弹):图书管理系统(用户登录+添加图书)
java·数据库·spring boot·mysql·面试·java-ee·mybatis
goyeer2 小时前
【Kubernetes】Kubernetes之CRI详解
java·容器·kubernetes
牧瀬クリスだ2 小时前
从零手写博客系统:分层架构与统一响应(一)
java·数据库·架构·mybatis·springboot·安全架构
Rain的Java大神之路3 小时前
LeetCode 40 组合总和 II:面试官想听的不是回溯,而是那行去重代码
java·leetcode·面试