在使用 Jackson 库进行 JSON 处理时,JavaType 类可以帮助你处理更复杂的类型转换,例如将
JSON 字符串转换为特定类型的集合或映射。以下是一个使用 JavaType 的工具类示例,它展示了
如何创建一个工具类来帮助进行这些转换。
Jackson JavaType 工具类
假设你已经有了一个 ObjectMapper 实例,并且想要创建一个工具类来简化一些常见的转换操作,
比如将 JSON 字符串转换为 List 或 Map 类型的对象。
-
import ;
-
import ;
-
import ;
-
-
import ;
-
import ;
-
-
public class JacksonJavaTypeUtils {
-
-
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
-
-
/**
-
* 将 JSON 字符串转换为指定类型的 Collection。
-
*
-
* @param jsonStr JSON 字符串
-
* @param elementType 元素类型
-
* @param <T> 泛型类型
-
* @return Collection<T>
-
* @throws Exception 如果转换失败
-
*/
-
public static <T> Collection<T> convertJsonToCollection(String jsonStr, Class<T> elementType) throws Exception {
-
JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructCollectionType(, elementType);
-
return OBJECT_MAPPER.readValue(jsonStr, javaType);
-
}
-
-
/**
-
* 将 JSON 字符串转换为指定类型的 Map。
-
*
-
* @param jsonStr JSON 字符串
-
* @param keyType 键类型
-
* @param valueType 值类型
-
* @param <K> 键泛型类型
-
* @param <V> 值泛型类型
-
* @return Map<K, V>
-
* @throws Exception 如果转换失败
-
*/
-
public static <K, V> Map<K, V> convertJsonToMap(String jsonStr, Class<K> keyType, Class<V> valueType) throws Exception {
-
JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructMapType(, keyType, valueType);
-
return OBJECT_MAPPER.readValue(jsonStr, javaType);
-
}
-
-
/**
-
* 将 JSON 字符串转换为指定类型的对象。
-
*
-
* @param jsonStr JSON 字符串
-
* @param clazz 目标类
-
* @param <T> 泛型类型
-
* @return T
-
* @throws Exception 如果转换失败
-
*/
-
public static <T> T convertJsonToObject(String jsonStr, Class<T> clazz) throws Exception {
-
return OBJECT_MAPPER.readValue(jsonStr, clazz);
-
}
-
-
/**
-
* 将 JSON 字符串转换为指定类型的对象列表。
-
*
-
* @param jsonStr JSON 字符串
-
* @param clazz 目标类
-
* @param <T> 泛型类型
-
* @return List<T>
-
* @throws Exception 如果转换失败
-
*/
-
public static <T> Collection<T> convertJsonToListOfObjects(String jsonStr, Class<T> clazz) throws Exception {
-
JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructCollectionType(, clazz);
-
return OBJECT_MAPPER.readValue(jsonStr, javaType);
-
}
-
-
/**
-
* 将 JSON 字符串转换为指定类型的 Map,其中键和值都是字符串。
-
*
-
* @param jsonStr JSON 字符串
-
* @return Map<String, String>
-
* @throws Exception 如果转换失败
-
*/
-
public static Map<String, String> convertJsonToStringMap(String jsonStr) throws Exception {
-
TypeReference<Map<String, String>> typeRef = new TypeReference<Map<String, String>>() {};
-
return OBJECT_MAPPER.readValue(jsonStr, typeRef);
-
}
-
}
使用示例
假设你有一个 JSON 字符串,表示一个用户列表:
String usersJson = "[{\"id\":1,\"name\":\"Alice\"},{\"id\":2,\"name\":\"Bob\"}]";
可以使用上面定义的工具类来将其转换为 List<User>:
-
import ;
-
-
public class User {
-
private int id;
-
private String name;
-
-
// Getters and setters
-
}
-
-
public class Main {
-
public static void main(String[] args) {
-
try {
-
List<User> users = (usersJson, );
-
(user -> (()));
-
} catch (Exception e) {
-
();
-
}
-
}
-
}
这个工具类提供了一些基本的方法来帮助你处理 JSON 字符串到 Java 对象的转换,你可以根据需
要扩展更多的方法。
如果你想使用 Jackson 将 JSON 字符串转换为一个包含泛型值的 CommonResult 类型,你可以通
过以下步骤实现:
定义 CommonResult 类,它应该包含一个泛型字段。
创建一个工具类,使用 JavaType 来构建正确的类型,并使用 ObjectMapper 的 readValue 方法来
完成转换。
下面是一个具体的实现示例:
CommonResult 类定义
首先定义 CommonResult 类,它包含一个泛型 data 字段:
-
public class CommonResult<T> {
-
private boolean success;
-
private String message;
-
private T data;
-
-
// 构造函数、getter 和 setter
-
public CommonResult() {}
-
-
public CommonResult(boolean success, String message, T data) {
-
this.success = success;
-
this.message = message;
-
this.data = data;
-
}
-
-
public boolean isSuccess() {
-
return success;
-
}
-
-
public void setSuccess(boolean success) {
-
this.success = success;
-
}
-
-
public String getMessage() {
-
return message;
-
}
-
-
public void setMessage(String message) {
-
this.message = message;
-
}
-
-
public T getData() {
-
return data;
-
}
-
-
public void setData(T data) {
-
this.data = data;
-
}
-
}
Jackson 类型转换工具类
接下来定义一个工具类,用于转换 JSON 字符串到 CommonResult 类型:
-
import ;
-
import ;
-
import ;
-
import ;
-
import ;
-
-
public class JacksonJavaTypeUtils {
-
-
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
-
-
/**
-
* 将 JSON 字符串转换为 CommonResult 类型。
-
*
-
* @param jsonStr JSON 字符串
-
* @param clazz 泛型数据的类型
-
* @param <T> 泛型类型
-
* @return CommonResult<T>
-
* @throws Exception 如果转换失败
-
*/
-
public static <T> CommonResult<T> convertJsonToCommonResult(String jsonStr, Class<T> clazz) throws Exception {
-
JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(, clazz);
-
return OBJECT_MAPPER.readValue(jsonStr, javaType);
-
}
-
}
假设你有一个 JSON 字符串,表示一个 CommonResult 对象,其中的数据部分是一个 User 类
型:
String userJson = "{\"success\":true,\"message\":\"OK\",\"data\":{\"id\":1,\"name\":\"Alice\"}}";
-
import ;
-
-
public class User {
-
private int id;
-
private String name;
-
-
// Getters and setters
-
}
-
-
public class Main {
-
public static void main(String[] args) {
-
try {
-
CommonResult<User> result = (userJson, );
-
if (()) {
-
User user = ();
-
("User ID: " + ());
-
("User Name: " + ());
-
} else {
-
("Error: " + ());
-
}
-
} catch (Exception e) {
-
();
-
}
-
}
-
}
在这个示例中,我们定义了一个 User 类,并使用 JacksonJavaTypeUtils 中的
convertJsonToCommonResult 方法来将 JSON 字符串转换为 CommonResult<User> 类型。
确保你的项目中已经包含了 Jackson 库的依赖。如果你使用的是 Maven,可以在 文件中
添加如下依赖:
-
<dependency>
-
<groupId></groupId>
-
<artifactId>jackson-databind</artifactId>
-
<version>2.13.4.2</version> <!-- 使用最新版本 -->
-
</dependency>
为了更好地支持将 JSON 字符串转换为 CommonResult 类型,我们可以进一步完善
JacksonJavaTypeUtils 工具类。下面是一个更新后的版本,它包括了错误处理和一些额外的功
能,例如转换JSON字符串到 CommonResult 的列表。
更新后的JacksonJavaTypeUtils工具类
-
import ;
-
import ;
-
import ;
-
import ;
-
import ;
-
-
public class JacksonJavaTypeUtils {
-
-
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
-
-
/**
-
* 将 JSON 字符串转换为 CommonResult 类型。
-
*
-
* @param jsonStr JSON 字符串
-
* @param clazz 泛型数据的类型
-
* @param <T> 泛型类型
-
* @return CommonResult<T>
-
* @throws Exception 如果转换失败
-
*/
-
public static <T> CommonResult<T> convertJsonToCommonResult(String jsonStr, Class<T> clazz) throws Exception {
-
JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(, clazz);
-
return OBJECT_MAPPER.readValue(jsonStr, javaType);
-
}
-
-
/**
-
* 将 JSON 字符串转换为 CommonResult 的列表。
-
*
-
* @param jsonStr JSON 字符串
-
* @param clazz 泛型数据的类型
-
* @param <T> 泛型类型
-
* @return List<CommonResult<T>>
-
* @throws Exception 如果转换失败
-
*/
-
public static <T> Collection<CommonResult<T>> convertJsonToListOfCommonResults(String jsonStr, Class<T> clazz) throws Exception {
-
JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructCollectionType(,
-
OBJECT_MAPPER.getTypeFactory().constructParametricType(, clazz));
-
return OBJECT_MAPPER.readValue(jsonStr, javaType);
-
}
-
}
假设你有两个 JSON 字符串,分别表示一个 CommonResult 对象和一个 CommonResult 的列表,
其中的数据部分是一个 User 类型:
-
String singleUserJson = "{\"success\":true,\"message\":\"OK\",\"data\":{\"id\":1,\"name\":\"Alice\"}}";
-
String listUserJson = "[{\"success\":true,\"message\":\"OK\",\"data\":{\"id\":1,\"name\":\"Alice\"}},{\"success\":true,\"message\":\"OK\",\"data\":{\"id\":2,\"name\":\"Bob\"}}]";
你可以使用上面定义的工具类来将其转换为 CommonResult<User> 和
List<CommonResult<User>>:
-
import ;
-
-
public class User {
-
private int id;
-
private String name;
-
-
// Getters and setters
-
}
-
-
public class Main {
-
public static void main(String[] args) {
-
try {
-
// 转换单个 CommonResult
-
CommonResult<User> singleResult = (singleUserJson, );
-
if (()) {
-
User user = ();
-
("Single User ID: " + ());
-
("Single User Name: " + ());
-
} else {
-
("Single Error: " + ());
-
}
-
-
// 转换 CommonResult 的列表
-
Collection<CommonResult<User>> resultList = (listUserJson, );
-
for (CommonResult<User> result : resultList) {
-
if (()) {
-
User user = ();
-
("List User ID: " + ());
-
("List User Name: " + ());
-
} else {
-
("List Error: " + ());
-
}
-
}
-
} catch (Exception e) {
-
();
-
}
-
}
-
}
在这个示例中,我们定义了一个 User 类,并使用 JacksonJavaTypeUtils 中的
convertJsonToCommonResult 和 convertJsonToListOfCommonResults 方法来将 JSON 字符串转
换为 CommonResult<User> 和 List<CommonResult<User>> 类型。