1、使用JsonPath

它提供了类似 XPath 的语法来查询 JSON。

添加依赖(Maven):

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.9.0</version>
</dependency>

示例:

import com.jayway.jsonpath.JsonPath;

String json = "…"; // 你的 JSON 字符串
String type = JsonPath.read(json, "$.type");
String msg = JsonPath.read(json, "$.data.msg");
List atList = JsonPath.read(json, "$.data.atWxidList");

2、使用org.json

一个轻量级的 JSON 处理库。

添加依赖(Maven):

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20240303</version>
</dependency>

示例:

import org.json.JSONObject;

String json = "..."; // 你的 JSON 字符串
JSONObject jsonObject = new JSONObject(json);
String type = jsonObject.getString("type");
String msg = jsonObject.getJSONObject("data").getString("msg");

3.使用hutool.JSONUtil

hutool是一款强大的Java工具包,包含一系列的工具类,如字符串,时间,文件,http请求等,懒人必备,简单使用可看Hutool 使用详解_hutool工具包-CSDN博客

添加依赖(Maven):

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.11</version>
</dependency>

json处理实例:

//从 JSON 字符串转换为对象
String json = "{\"name\":\"张三\",\"age\":25}";
MyObject obj = JSONUtil.toBean(json, MyObject.class);
System.out.println(obj.getName());  // 输出 张三
//从 JSON 字符串转换为对象
String json = "{\"name\":\"张三\",\"age\":25}";
String prettyJson = JSONUtil.toJsonStr(JSONUtil.parseObj(json), true);
System.out.println(prettyJson); 
// 输出:
// {
//     "name": "张三",
//     "age": 25
// }
//操作 JSON 对象
String json = "{\"name\":\"张三\",\"age\":25}";
JSONObject jsonObject = JSONUtil.parseObj(json);
String name = jsonObject.getStr("name");
System.out.println(name);  // 输出 张三
//合并JSON对象
// 第一个 JSON 对象
String json1 = "{\"name\":\"张三\",\"age\":25}";
JSONObject jsonObject1 = JSONUtil.parseObj(json1);
// 第二个 JSON 对象
String json2 = "{\"address\":\"北京\",\"phone\":\"123456789\"}";
JSONObject jsonObject2 = JSONUtil.parseObj(json2);
// 合并两个 JSON 对象
jsonObject1.merge(jsonObject2);
System.out.println(jsonObject1);  
// 输出:{"name":"张三","age":25,"address":"北京","phone":"123456789"}
//删除JSON对象某个属性
String json = "{\"name\":\"张三\",\"age\":25,\"address\":\"北京\"}";
JSONObject jsonObject = JSONUtil.parseObj(json);
// 删除字段
jsonObject.remove("address");
//批量删除 jsonObject.removeAll(Arrays.asList("address", "age"));
System.out.println(jsonObject);  // 输出:{"name":"张三","age":25}
此作者没有提供个人介绍
最后更新于 2025-02-17