欧易下载
欧易交易所
<欧易官方
欧易app
欧易下载
欧易交易所
欧易官方
欧易app
chrome浏览器
谷歌浏览器
快连下载
快连下载
快连下载
chrome浏览器
谷歌浏览器
快连下载
快连下载
快连下载
快连
快连
快连
快连下载
whatsapp网页版
whatsapp网页版
whatsapp网页版
whatsapp网页版
快连
快连
快连下载
whatsapp网页版
whatsapp网页版
whatsapp网页版
whatsapp网页版
Java代码中如何优雅地处理JSON:从基础到实践
在当今的软件开发中,JSON(JavaScript Object Notation)已成为数据交换的事实标准,无论是前后端接口通信、配置文件存储,还是微服务间的数据传递,JSON都以其轻量、易读、易解析的特性被广泛应用,作为Java开发者,在代码中高效处理JSON的方法至关重要,本文将从基础概念出发,结合主流工具库,详细讲解Java代码中如何读写、解析和生成JSON,并附实用示例。
JSON与Java:基础概念对应
在代码实践前,先明确JSON与Java数据结构的对应关系,这有助于理解后续的操作逻辑:
| JSON类型 | Java类型 | 说明 |
|---|---|---|
| 对象() | Map / 自定义Java类 |
键值对集合,键为String,值为任意JSON类型 |
数组([]) |
List / 数组 |
有序集合,元素可为任意JSON类型 |
| 字符串() | String |
双引号包裹的文本 |
| 数字 | Integer / Long / Double |
整数、长整、浮点数等 |
| 布尔值 | Boolean |
true / false |
空值(null) |
null |
无值 |
Java处理JSON的三大主流工具库
Java生态中处理JSON的工具有很多,目前主流且推荐的有三种:Jackson、Gson 和 Fastjson(阿里开源),本文将重点讲解前两者,Fastjson因其历史漏洞问题,新项目已较少使用,但仍会简要提及。
(一)Jackson:功能强大的“全能选手”
Jackson是Java生态中最流行的JSON库之一,被Spring Boot等主流框架作为默认JSON处理器,它不仅性能优秀,还支持复杂对象映射、流式处理等高级特性。
添加依赖
Maven项目添加:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version> <!-- 使用最新版本 -->
</dependency>
Java对象转JSON(序列化)
使用 ObjectMapper 将Java对象转换为JSON字符串。
示例:自定义Java类转JSON
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
// 定义用户类
class User {
private String name;
private int age;
private String[] hobbies;
// 无参构造器(Jackson反射需要)
public User() {}
// 有参构造器
public User(String name, int age, String[] hobbies) {
this.name = name;
this.age = age;
this.hobbies = hobbies;
}
// Getter和Setter(Jackson反射需要)
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public String[] getHobbies() { return hobbies; }
public void setHobbies(String[] hobbies) { this.hobbies = hobbies; }
}
public class JacksonExample {
public static void main(String[] args) throws JsonProcessingException {
User user = new User("张三", 25, new String[]{"篮球", "编程"});
// 创建ObjectMapper实例
ObjectMapper mapper = new ObjectMapper();
// 将User对象转为JSON字符串(格式化输出)
String jsonStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user);
System.out.println(jsonStr);
// 输出:
// {
// "name" : "张三",
// "age" : 25,
// "hobbies" : [ "篮球", "编程" ]
// }
}
}
JSON转Java对象(反序列化)
将JSON字符串解析为Java对象。
示例:JSON字符串转User对象
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonDeserializeExample {
public static void main(String[] args) throws JsonProcessingException {
String jsonStr = "{\"name\":\"李四\",\"age\":30,\"hobbies\":[\"阅读\",\"旅行\"]}";
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(jsonStr, User.class);
System.out.println("用户名:" + user.getName()); // 输出:用户名:李四
System.out.println("年龄:" + user.getAge()); // 输出:年龄:30
System.out.println("爱好:" + String.join(", ", user.getHobbies())); // 输出:爱好:阅读, 旅行
}
}
处理复杂场景:List/Map转JSON
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
import java.util.Map;
public class JacksonComplexExample {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
// List转JSON
List<String> hobbies = List.of("游泳", "摄影");
String listJson = mapper.writeValueAsString(hobbies);
System.out.println("List转JSON: " + listJson); // 输出:List转JSON: ["游泳","摄影"]
// JSON转List
List<String> parsedHobbies = mapper.readValue(listJson, new TypeReference<List<String>>() {});
System.out.println("JSON转List: " + parsedHobbies); // 输出:JSON转List: [游泳, 摄影]
// Map转JSON
Map<String, Object> data = Map.of("name", "王五", "age", 28, "isStudent", false);
String mapJson = mapper.writeValueAsString(data);
System.out.println("Map转JSON: " + mapJson); // 输出:Map转JSON: {"name":"王五","age":28,"isStudent":false}
// JSON转Map
Map<String, Object> parsedData = mapper.readValue(mapJson, new TypeReference<Map<String, Object>>() {});
System.out.println("JSON转Map: " + parsedData); // 输出:JSON转Map: {name=王五, age=28, isStudent=false}
}
}
Jackson注解:灵活控制JSON映射
Jackson提供了丰富的注解,用于自定义JSON与Java对象的映射规则:
| 注解 | 作用 | 示例 |
|---|---|---|
@JsonProperty |
指定JSON字段与Java属性的映射关系 | @JsonProperty("userName") private String name; |
@JsonIgnore |
忽略某个属性(不参与序列化/反序列化) | @JsonIgnore private String password; |
@JsonFormat |
格式化日期/数字等类型 | @JsonFormat(pattern = "yyyy-MM-dd") private Date birthDate; |
@JsonCreator |
自定义构造器(反序列化时使用) | 见下方示例 |
示例:使用注解
import com.fasterxml.jackson.annotation.*;
class UserWithAnnotation {
@JsonProperty("user_name")
private String name;
@JsonIgnore
private String password;
@JsonFormat(pattern = "yyyy-MM-dd")
private Date birthDate;
// 使用@JsonCreator自定义构造器(适用于反序列化时无参构造器不可用的情况)
@JsonCreator
public UserWithAnnotation(@JsonProperty("user_name") String name) {
this.name = name;
}
// Getter/Setter
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Date getBirthDate() { return birthDate; }
public void setBirthDate(Date birthDate) { this.birthDate = birthDate; }
}
(二)Gson:Google出品,简洁易用
Gson是Google开发的JSON库,以API简洁、易上手著称,特别适合中小型项目。
添加依赖
Maven项目添加:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version> <!-- 使用最新版本 -->
</dependency>
Java对象转JSON(序列化)
使用 Gson 实例的 toJson() 方法。
示例:
import com.google.gson.Gson;
class User {
private String name;
private int age;
private String[] hobbies;
public User(String name, int age, String[] hobbies) {
this.name = name;
this.age = age;
this.hobbies = hobbies;
}
// Getter/Setter
public String getName() { return name; }
public void setName(String name) { this.name = name


还没有评论,来说两句吧...