常见的用Java来解析复杂Json的例子

解析复杂的JSON字符串在Java中可以通过多种工具和库来实现。常用的库包括Jackson、Gson和org.json等。以下是使用各种库的示例来解析复杂的JSON字符串。

使用Jackson

Jackson是一个非常流行的JSON处理库,非常适合解析复杂的JSON结构。

依赖

首先,确保在你的项目中包含Jackson的依赖。例如,在Maven项目中,你可以在pom.xml添加以下依赖:

xml 复制代码
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.1</version>
</dependency>
示例JSON

假设有以下复杂的JSON字符串:

json 复制代码
{
  "id": 1,
  "projectName": "Example Project",
  "details": {
    "description": "This is a sample project",
    "fileDetails": [
      {
        "fileUrl": "https://example.com/files/document1.pdf",
        "fileName": "document1.pdf",
        "fileSize": "2048KB"
      },
      {
        "fileUrl": "https://example.com/files/document2.pdf",
        "fileName": "document2.pdf",
        "fileSize": "1024KB"
      }
    ]
  },
  "metaData": {
    "createdAt": "2021-10-24T14:48:00.000Z",
    "updatedAt": "2021-11-24T14:48:00.000Z"
  }
}
Java对象

根据JSON结构,定义相应的Java类来映射这些数据:

java 复制代码
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

public class ImportFileDetailRequest {
    @JsonProperty("fileUrl")
    private String fileUrl;

    @JsonProperty("fileName")
    private String fileName;

    @JsonProperty("fileSize")
    private String fileSize;

    // Getters and Setters
}

public class Details {
    @JsonProperty("description")
    private String description;

    @JsonProperty("fileDetails")
    private List<ImportFileDetailRequest> fileDetails;

    // Getters and Setters
}

public class MetaData {
    @JsonProperty("createdAt")
    private String createdAt;
    
    @JsonProperty("updatedAt")
    private String updatedAt;
    
    // Getters and Setters
}

public class Project {
    @JsonProperty("id")
    private int id;

    @JsonProperty("projectName")
    private String projectName;

    @JsonProperty("details")
    private Details details;

    @JsonProperty("metaData")
    private MetaData metaData;

    // Getters and Setters
}
解析JSON

使用Jackson的ObjectMapper类来解析JSON字符串:

java 复制代码
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonParserExample {
    public static void main(String[] args) {
        String jsonString = "{ \"id\": 1, \"projectName\": \"Example Project\", \"details\": { \"description\": \"This is a sample project\", \"fileDetails\": [ { \"fileUrl\": \"https://example.com/files/document1.pdf\", \"fileName\": \"document1.pdf\", \"fileSize\": \"2048KB\" }, { \"fileUrl\": \"https://example.com/files/document2.pdf\", \"fileName\": \"document2.pdf\", \"fileSize\": \"1024KB\" } ] }, \"metaData\": { \"createdAt\": \"2021-10-24T14:48:00.000Z\", \"updatedAt\": \"2021-11-24T14:48:00.000Z\" }}";

        ObjectMapper objectMapper = new ObjectMapper();

        try {
            Project project = objectMapper.readValue(jsonString, Project.class);
            System.out.println("Project Name: " + project.getProjectName());
            System.out.println("File Details: " + project.getDetails().getFileDetails());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

使用Gson

Gson是另一个流行的JSON解析库。

依赖

确保在你的项目中包含Gson的依赖。例如,在Maven项目中:

xml 复制代码
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.8</version>
</dependency>
解析JSON

使用Gson来解析相同的JSON字符串:

java 复制代码
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        String jsonString = "{ \"id\": 1, \"projectName\": \"Example Project\", \"details\": { \"description\": \"This is a sample project\", \"fileDetails\": [ { \"fileUrl\": \"https://example.com/files/document1.pdf\", \"fileName\": \"document1.pdf\", \"fileSize\": \"2048KB\" }, { \"fileUrl\": \"https://example.com/files/document2.pdf\", \"fileName\": \"document2.pdf\", \"fileSize\": \"1024KB\" } ] }, \"metaData\": { \"createdAt\": \"2021-10-24T14:48:00.000Z\", \"updatedAt\": \"2021-11-24T14:48:00.000Z\" }}";

        Gson gson = new Gson();
        Project project = gson.fromJson(jsonString, Project.class);
        
        System.out.println("Project Name: " + project.getProjectName());
        System.out.println("File Details: " + project.getDetails().getFileDetails());
    }
}

class ImportFileDetailRequest {
    @SerializedName("fileUrl")
    private String fileUrl;

    @SerializedName("fileName")
    private String fileName;

    @SerializedName("fileSize")
    private String fileSize;

    // Getters and Setters
}

class Details {
    @SerializedName("description")
    private String description;

    @SerializedName("fileDetails")
    private List<ImportFileDetailRequest> fileDetails;

    // Getters and Setters
}

class MetaData {
    @SerializedName("createdAt")
    private String createdAt;
    
    @SerializedName("updatedAt")
    private String updatedAt;
    
    // Getters and Setters
}

class Project {
    @SerializedName("id")
    private int id;

    @SerializedName("projectName")
    private String projectName;

    @SerializedName("details")
    private Details details;

    @SerializedName("metaData")
    private MetaData metaData;

    // Getters and Setters
}

使用org.json

org.json库提供了较为直接的方式来操作JSON对象。

依赖

确保在你的项目中包含org.json依赖。例如,在Maven项目中:

xml 复制代码
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20210307</version>
</dependency>
解析JSON

使用JSONObjectJSONArray来解析JSON字符串:

java 复制代码
import org.json.JSONArray;
import org.json.JSONObject;

public class JsonParserUsingOrgJson {
    public static void main(String[] args) {
        String jsonString = "{ \"id\": 1, \"projectName\": \"Example Project\", \"details\": { \"description\": \"This is a sample project\", \"fileDetails\": [ { \"fileUrl\": \"https://example.com/files/document1.pdf\", \"fileName\": \"document1.pdf\", \"fileSize\": \"2048KB\" }, { \"fileUrl\": \"https://example.com/files/document2.pdf\", \"fileName\": \"document2.pdf\", \"fileSize\": \"1024KB\" } ] }, \"metaData\": { \"createdAt\": \"2021-10-24T14:48:00.000Z\", \"updatedAt\": \"2021-11-24T14:48:00.000Z\" }}";

        JSONObject jsonObject = new JSONObject(jsonString);

        int id = jsonObject.getInt("id");
        String projectName = jsonObject.getString("projectName");
        JSONObject details = jsonObject.getJSONObject("details");
        String description = details.getString("description");
        JSONArray fileDetails = details.getJSONArray("fileDetails");

        System.out.println("Project ID: " + id);
        System.out.println("Project Name: " + projectName);
        System.out.println("Description: " + description);
        for (int i = 0; i < fileDetails.length(); i++) {
            JSONObject fileDetail = fileDetails.getJSONObject(i);
            System.out.println("File URL: " + fileDetail.getString("fileUrl"));
            System.out.println("File Name: " + fileDetail.getString("fileName"));
            System.out.println("File Size: " + fileDetail.getString("fileSize"));
        }

        JSONObject metaData = jsonObject.getJSONObject("metaData");
        String createdAt = metaData.getString("createdAt");
        String updatedAt = metaData.getString("updatedAt");

        System.out.println("Created At: " + createdAt);
        System.out.println("Updated At: " + updatedAt);
    }
}

使用Hutool.JSONUtil

Hutool 是一个功能强大且轻量级的 Java 工具库,提供了丰富的工具类,其中 JSONUtil 类可以方便地解析和操作 JSON 数据。下面是使用 Hutool 解析复杂 JSON 字符串的完整示例。

示例 JSON 字符串

假设有以下复杂的 JSON 字符串:

json 复制代码
{
  "id": 1,
  "projectName": "Example Project",
  "details": {
    "description": "This is a sample project",
    "fileDetails": [
      {
        "fileUrl": "https://example.com/files/document1.pdf",
        "fileName": "document1.pdf",
        "fileSize": "2048KB"
      },
      {
        "fileUrl": "https://example.com/files/document2.pdf",
        "fileName": "document2.pdf",
        "fileSize": "1024KB"
      }
    ]
  },
  "metaData": {
    "createdAt": "2021-10-24T14:48:00.000Z",
    "updatedAt": "2021-11-24T14:48:00.000Z"
  }
}

添加 Hutool 依赖

确保在你的项目中包含 Hutool 的依赖。例如,在 Maven 项目中,你可以在 pom.xml 文件中添加以下依赖:

xml 复制代码
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.7.17</version>
</dependency>

定义 Java 类

定义与 JSON 结构对应的 Java 类:

java 复制代码
import cn.hutool.core.annotation.Alias;
import java.util.List;

public class ImportFileDetailRequest {
    @Alias("fileUrl")
    private String fileUrl;

    @Alias("fileName")
    private String fileName;

    @Alias("fileSize")
    private String fileSize;

    // Getters and Setters
}

public class Details {
    @Alias("description")
    private String description;

    @Alias("fileDetails")
    private List<ImportFileDetailRequest> fileDetails;

    // Getters and Setters
}

public class MetaData {
    @Alias("createdAt")
    private String createdAt;
    
    @Alias("updatedAt")
    private String updatedAt;
    
    // Getters and Setters
}

public class Project {
    @Alias("id")
    private int id;

    @Alias("projectName")
    private String projectName;

    @Alias("details")
    private Details details;

    @Alias("metaData")
    private MetaData metaData;

    // Getters and Setters
}

解析 JSON

使用 Hutool 的 JSONUtil 类来解析 JSON 字符串:

java 复制代码
import cn.hutool.json.JSONUtil;

public class JsonParserExample {
    public static void main(String[] args) {
        String jsonString = "{ \"id\": 1, \"projectName\": \"Example Project\", \"details\": { \"description\": \"This is a sample project\", \"fileDetails\": [ { \"fileUrl\": \"https://example.com/files/document1.pdf\", \"fileName\": \"document1.pdf\", \"fileSize\": \"2048KB\" }, { \"fileUrl\": \"https://example.com/files/document2.pdf\", \"fileName\": \"document2.pdf\", \"fileSize\": \"1024KB\" } ] }, \"metaData\": { \"createdAt\": \"2021-10-24T14:48:00.000Z\", \"updatedAt\": \"2021-11-24T14:48:00.000Z\" }}";

        // 解析 JSON 字符串
        Project project = JSONUtil.toBean(jsonString, Project.class);

        // 输出解析结果
        System.out.println("Project Name: " + project.getProjectName());
        System.out.println("Description: " + project.getDetails().getDescription());
        for (ImportFileDetailRequest fileDetail : project.getDetails().getFileDetails()) {
            System.out.println("File URL: " + fileDetail.getFileUrl());
            System.out.println("File Name: " + fileDetail.getFileName());
            System.out.println("File Size: " + fileDetail.getFileSize());
        }
        System.out.println("Created at: " + project.getMetaData().getCreatedAt());
        System.out.println("Updated at: " + project.getMetaData().getUpdatedAt());
    }
}

逐步解析JSON

如果不想映射成Java对象,可以使用JSONObjectJSONArray逐步解析:

java 复制代码
import cn.hutool.json.JSONUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONArray;
import java.util.List;

public class JsonParserStepByStep {
    public static void main(String[] args) {
        String jsonString = "{ \"id\": 1, \"projectName\": \"Example Project\", \"details\": { \"description\": \"This is a sample project\", \"fileDetails\": [ { \"fileUrl\": \"https://example.com/files/document1.pdf\", \"fileName\": \"document1.pdf\", \"fileSize\": \"2048KB\" }, { \"fileUrl\": \"https://example.com/files/document2.pdf\", \"fileName\": \"document2.pdf\", \"fileSize\": \"1024KB\" } ] }, \"metaData\": { \"createdAt\": \"2021-10-24T14:48:00.000Z\", \"updatedAt\": \"2021-11-24T14:48:00.000Z\" }}";

        // 将字符串转成JSONObject对象
        JSONObject jsonObject = JSONUtil.parseObj(jsonString);

        // 逐步解析数据
        int id = jsonObject.getInt("id");
        String projectName = jsonObject.getStr("projectName");

        JSONObject details = jsonObject.getJSONObject("details");
        String description = details.getStr("description");
        JSONArray fileDetails = details.getJSONArray("fileDetails");

        System.out.println("Project ID: " + id);
        System.out.println("Project Name: " + projectName);
        System.out.println("Description: " + description);
        for (int i = 0; i < fileDetails.size(); i++) {
            JSONObject fileDetail = fileDetails.getJSONObject(i);
            String fileUrl = fileDetail.getStr("fileUrl");
            String fileName = fileDetail.getStr("fileName");
            String fileSize = fileDetail.getStr("fileSize");
            System.out.println("File URL: " + fileUrl);
            System.out.println("File Name: " + fileName);
            System.out.println("File Size: " + fileSize);
        }

        JSONObject metaData = jsonObject.getJSONObject("metaData");
        String createdAt = metaData.getStr("createdAt");
        String updatedAt = metaData.getStr("updatedAt");

        System.out.println("Created At: " + createdAt);
        System.out.println("Updated At: " + updatedAt);
    }
}

总结

上述示例分别展示了如何使用Jackson、Gson和org.json库以及Hutool的JSONUtil类来解析复杂的JSON字符串。根据你的需求和喜好选择合适的库,合理定义Java对象,并结合库的特点来进行JSON解析。Jackson和Gson更适合映射复杂对象,org.json则适合直接操作。

相关推荐
dandanforgetlove39 分钟前
python pdfplumber优化表格提取
开发语言·windows·python
ka2x40 分钟前
订单折扣金额分摊算法|代金券分摊|收银系统|积分分摊|分摊|精度问题|按比例分配|钱分摊|钱分配
java·c语言·c++·python·算法·spring·spring cloud
小奥超人2 小时前
PPT文件中,母版视图与修改权限的区别
windows·经验分享·powerpoint·办公技巧
职略3 小时前
负载均衡类型和算法解析
java·运维·分布式·算法·负载均衡
A22743 小时前
LeetCode 196, 73, 105
java·算法·leetcode
容若只如初见4 小时前
项目实战--Spring Boot + Minio文件切片上传下载
java·spring boot·后端
阿里巴巴P8资深技术专家4 小时前
Java常用算法&集合扩容机制分析
java·数据结构·算法
weixin_440401694 小时前
分布式锁——基于Redis分布式锁
java·数据库·spring boot·redis·分布式
码农爱java4 小时前
Spring Boot 中的监视器是什么?有什么作用?
java·spring boot·后端·面试·monitor·监视器
zengson_g4 小时前
当需要对大量数据进行排序操作时,怎样优化内存使用和性能?
java·数据库·算法·排序算法