Java JSON与集合转换
在现代Java应用开发中,JSON(JavaScript Object Notation)作为一种轻量级的数据交换格式,已成为前后端数据传输的标准格式。而Java集合框架是Java程序处理数据的核心容器。因此,掌握JSON与Java集合之间的转换技术是每位Java开发者必备的基础技能。
JSON与集合的关系
在理解转换之前,我们先来看看JSON与Java集合的结构对应关系:
JSON对象(用{}
表示)通常对应Java中的Map或实体类(POJO)
JSON数组(用[]
表示)通常对应Java中的List或数组
常用的JSON处理库
在Java中,常用的JSON库有:
- Jackson - Spring Boot默认的JSON库
- Gson - 由Google开发的JSON库
- fastjson - 阿里巴巴开发的高性能JSON库
- org.json - 简单易用的JSON库
本文我们主要介绍Jackson和Gson的使用方法,这也是目前使用最广泛的两个库。
Jackson库实现JSON与集合转换
添加依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
List集合与JSON转换
List转JSON
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.List;
public class ListToJsonExample {
public static void main(String[] args) throws Exception {
// 创建ObjectMapper对象
ObjectMapper mapper = new ObjectMapper();
// 创建List集合
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
// 将List转换为JSON字符串
String jsonString = mapper.writeValueAsString(fruits);
System.out.println("List转换为JSON: " + jsonString);
}
}
输出结果:
List转换为JSON: ["Apple","Banana","Orange"]
JSON转List
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
public class JsonToListExample {
public static void main(String[] args) throws Exception {
// 创建ObjectMapper对象
ObjectMapper mapper = new ObjectMapper();
// JSON字符串
String jsonString = "[\"Apple\",\"Banana\",\"Orange\"]";
// 将JSON字符串转换为List
List<String> fruits = mapper.readValue(jsonString, new TypeReference<List<String>>(){});
System.out.println("JSON转换为List: " + fruits);
}
}
输出结果:
JSON转换为List: [Apple, Banana, Orange]
Map集合与JSON转换
Map转JSON
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
public class MapToJsonExample {
public static void main(String[] args) throws Exception {
// 创建ObjectMapper对象
ObjectMapper mapper = new ObjectMapper();
// 创建Map集合
Map<String, Object> person = new HashMap<>();
person.put("name", "张三");
person.put("age", 25);
person.put("isStudent", false);
// 将Map转换为JSON字符串
String jsonString = mapper.writeValueAsString(person);
System.out.println("Map转换为JSON: " + jsonString);
}
}
输出结果:
Map转换为JSON: {"name":"张三","age":25,"isStudent":false}
JSON转Map
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
public class JsonToMapExample {
public static void main(String[] args) throws Exception {
// 创建ObjectMapper对象
ObjectMapper mapper = new ObjectMapper();
// JSON字符串
String jsonString = "{\"name\":\"张三\",\"age\":25,\"isStudent\":false}";
// 将JSON字符串转换为Map
Map<String, Object> person = mapper.readValue(jsonString, new TypeReference<Map<String, Object>>(){});
System.out.println("JSON转换为Map: " + person);
System.out.println("姓名: " + person.get("name"));
System.out.println("年龄: " + person.get("age"));
}
}
输出结果:
JSON转换为Map: {name=张三, age=25, isStudent=false}
姓名: 张三
年龄: 25
复杂嵌套集合与JSON转换
现实应用中,我们经常需要处理嵌套的集合结构,如下所示:
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.*;
public class NestedCollectionExample {
public static void main(String[] args) throws Exception {
// 创建ObjectMapper对象
ObjectMapper mapper = new ObjectMapper();
// 创建复杂嵌套集合
Map<String, Object> course = new HashMap<>();
course.put("name", "Java编程");
course.put("teacher", "李教授");
List<Map<String, Object>> students = new ArrayList<>();
Map<String, Object> student1 = new HashMap<>();
student1.put("name", "张三");
student1.put("score", 85);
Map<String, Object> student2 = new HashMap<>();
student2.put("name", "李四");
student2.put("score", 92);
students.add(student1);
students.add(student2);
course.put("students", students);
// 转换为JSON
String jsonString = mapper.writeValueAsString(course);
System.out.println("复杂集合转JSON:\n" + jsonString);
// JSON转回复杂集合
Map<String, Object> parsedCourse = mapper.readValue(jsonString,
new TypeReference<Map<String, Object>>(){});
// 获取嵌套的学生列表
List<Map<String, Object>> parsedStudents =
mapper.convertValue(parsedCourse.get("students"),
new TypeReference<List<Map<String, Object>>>(){});
System.out.println("\n解析后的学生列表:");
for (Map<String, Object> student : parsedStudents) {
System.out.println(" 学生: " + student.get("name") + ", 分数: " + student.get("score"));
}
}
}
输出结果:
复杂集合转JSON:
{"name":"Java编程","teacher":"李教授","students":[{"name":"张三","score":85},{"name":"李四","score":92}]}
解析后的学生列表:
学生: 张三, 分数: 85
学生: 李四, 分数: 92
Gson库实现JSON与集合转换
添加依赖
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
List集合与JSON转换
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class GsonListExample {
public static void main(String[] args) {
Gson gson = new Gson();
// List转JSON
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
String jsonString = gson.toJson(fruits);
System.out.println("List转JSON: " + jsonString);
// JSON转List
Type fruitListType = new TypeToken<List<String>>(){}.getType();
List<String> fruitsList = gson.fromJson(jsonString, fruitListType);
System.out.println("JSON转List: " + fruitsList);
}
}
输出结果:
List转JSON: ["Apple","Banana","Orange"]
JSON转List: [Apple, Banana, Orange]
Map集合与JSON转换
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
public class GsonMapExample {
public static void main(String[] args) {
Gson gson = new Gson();
// Map转JSON
Map<String, Object> person = new HashMap<>();
person.put("name", "张三");
person.put("age", 25);
person.put("isStudent", false);
String jsonString = gson.toJson(person);
System.out.println("Map转JSON: " + jsonString);
// JSON转Map
Type personMapType = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, Object> personMap = gson.fromJson(jsonString, personMapType);
System.out.println("JSON转Map: " + personMap);
System.out.println("姓名: " + personMap.get("name"));
}
}
输出结果:
Map转JSON: {"name":"张三","age":25,"isStudent":false}
JSON转Map: {name=张三, age=25.0, isStudent=false}
姓名: 张三
注意Gson在处理数值时默认会将整数转换为double类型,这点与Jackson有所不同。
实际应用场景
场景一:处理RESTful API响应
在与REST API交互时,我们经常需要处理JSON格式的响应数据:
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;
public class ApiResponseExample {
public static void main(String[] args) throws Exception {
// 创建HTTP客户端
HttpClient client = HttpClient.newHttpClient();
// 创建HTTP请求
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/users"))
.build();
// 发送请求并获取响应
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
// 解析JSON响应
ObjectMapper mapper = new ObjectMapper();
List<Map<String, Object>> users = mapper.readValue(response.body(),
new TypeReference<List<Map<String, Object>>>(){});
// 输出用户数据
System.out.println("获取到 " + users.size() + " 个用户");
for (Map<String, Object> user : users) {
System.out.println("用户ID: " + user.get("id") +
", 姓名: " + user.get("name") +
", 邮箱: " + user.get("email"));
// 获取嵌套对象
Map<String, Object> address = mapper.convertValue(user.get("address"),
new TypeReference<Map<String, Object>>(){});
System.out.println(" 地址: " + address.get("street") + ", " + address.get("city"));
}
}
}
场景二:配置管理
应用程序中常常需要读取或保存配置信息,JSON是常用的配置文件格式:
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class ConfigurationExample {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
// 创建配置信息
Map<String, Object> config = new HashMap<>();
config.put("appName", "MyJavaApp");
config.put("version", "1.0.0");
Map<String, Object> database = new HashMap<>();
database.put("url", "jdbc:mysql://localhost:3306/mydb");
database.put("username", "admin");
database.put("password", "********");
config.put("database", database);
// 保存配置到文件
mapper.writerWithDefaultPrettyPrinter()
.writeValue(new File("config.json"), config);
System.out.println("配置已保存到config.json文件");
// 从文件读取配置
Map<String, Object> loadedConfig = mapper.readValue(new File("config.json"),
new TypeReference<Map<String, Object>>(){});
System.out.println("应用名称: " + loadedConfig.get("appName"));
System.out.println("版本: " + loadedConfig.get("version"));
// 读取嵌套配置
Map<String, Object> dbConfig = mapper.convertValue(loadedConfig.get("database"),
new TypeReference<Map<String, Object>>(){});
System.out.println("数据库URL: " + dbConfig.get("url"));
}
}
最佳实践与注意事项
-
选择合适的库: 根据项目需求选择合适的JSON库,Spring Boot项目推荐使用Jackson,Android项目可以考虑使用Gson。
-
类型安全: 使用泛型和TypeReference确保类型安全,避免运行时类型转换错误。
-
性能考虑:
- 对于大型JSON处理,考虑使用流式API
- 频繁使用的对象,可以重用ObjectMapper实例而不是每次创建新的
-
日期处理: JSON标准中没有日期类型,需要特别处理Java中的日期类型。
// Jackson日期处理示例
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
// 或者使用Java 8时间模块
mapper.registerModule(new JavaTimeModule());
- 空值处理: 默认情况下,Jackson会序列化null值,Gson会忽略null值。
// Jackson配置忽略null值
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
小结
本文详细介绍了Java中JSON与集合的互相转换方法,重点讲解了以下内容:
- JSON与Java集合类型的对应关系
- 使用Jackson实现List、Map与JSON的转换
- 使用Gson实现集合与JSON的转换
- 复杂嵌套集合的JSON处理
- 实际应用场景示例
- 最佳实践和注意事项
掌握JSON与集合的转换技术,将帮助你更高效地开发Web应用、处理API数据,以及实现数据持久化。
练习
-
创建一个包含多种嵌套集合的数据结构(如List中包含Map,Map中又包含List等),并将其转换为JSON,然后再转换回Java对象。
-
使用Jackson或Gson读取一个REST API(如https://jsonplaceholder.typicode.com/posts),将返回的JSON数据解析为Java集合,并提取特定字段进行操作。
-
创建一个简单的配置管理系统,能够将应用配置保存为JSON文件,并且能够从文件中读取配置信息到Java应用中。
扩展阅读
通过这些资源,你可以进一步深入学习JSON处理技术,开发更强大的Java应用。