Json-jackson中JavaType转换工具类

时间:2025-01-20 14:22:00

在使用 Jackson 库进行 JSON 处理时,JavaType 类可以帮助你处理更复杂的类型转换,例如将

JSON 字符串转换为特定类型的集合或映射。以下是一个使用 JavaType 的工具类示例,它展示了

如何创建一个工具类来帮助进行这些转换。

Jackson JavaType 工具类

假设你已经有了一个 ObjectMapper 实例,并且想要创建一个工具类来简化一些常见的转换操作,

比如将 JSON 字符串转换为 List 或 Map 类型的对象。

  1. import ;
  2. import ;
  3. import ;
  4. import ;
  5. import ;
  6. public class JacksonJavaTypeUtils {
  7. private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
  8. /**
  9. * 将 JSON 字符串转换为指定类型的 Collection。
  10. *
  11. * @param jsonStr JSON 字符串
  12. * @param elementType 元素类型
  13. * @param <T> 泛型类型
  14. * @return Collection<T>
  15. * @throws Exception 如果转换失败
  16. */
  17. public static <T> Collection<T> convertJsonToCollection(String jsonStr, Class<T> elementType) throws Exception {
  18. JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructCollectionType(, elementType);
  19. return OBJECT_MAPPER.readValue(jsonStr, javaType);
  20. }
  21. /**
  22. * 将 JSON 字符串转换为指定类型的 Map。
  23. *
  24. * @param jsonStr JSON 字符串
  25. * @param keyType 键类型
  26. * @param valueType 值类型
  27. * @param <K> 键泛型类型
  28. * @param <V> 值泛型类型
  29. * @return Map<K, V>
  30. * @throws Exception 如果转换失败
  31. */
  32. public static <K, V> Map<K, V> convertJsonToMap(String jsonStr, Class<K> keyType, Class<V> valueType) throws Exception {
  33. JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructMapType(, keyType, valueType);
  34. return OBJECT_MAPPER.readValue(jsonStr, javaType);
  35. }
  36. /**
  37. * 将 JSON 字符串转换为指定类型的对象。
  38. *
  39. * @param jsonStr JSON 字符串
  40. * @param clazz 目标类
  41. * @param <T> 泛型类型
  42. * @return T
  43. * @throws Exception 如果转换失败
  44. */
  45. public static <T> T convertJsonToObject(String jsonStr, Class<T> clazz) throws Exception {
  46. return OBJECT_MAPPER.readValue(jsonStr, clazz);
  47. }
  48. /**
  49. * 将 JSON 字符串转换为指定类型的对象列表。
  50. *
  51. * @param jsonStr JSON 字符串
  52. * @param clazz 目标类
  53. * @param <T> 泛型类型
  54. * @return List<T>
  55. * @throws Exception 如果转换失败
  56. */
  57. public static <T> Collection<T> convertJsonToListOfObjects(String jsonStr, Class<T> clazz) throws Exception {
  58. JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructCollectionType(, clazz);
  59. return OBJECT_MAPPER.readValue(jsonStr, javaType);
  60. }
  61. /**
  62. * 将 JSON 字符串转换为指定类型的 Map,其中键和值都是字符串。
  63. *
  64. * @param jsonStr JSON 字符串
  65. * @return Map<String, String>
  66. * @throws Exception 如果转换失败
  67. */
  68. public static Map<String, String> convertJsonToStringMap(String jsonStr) throws Exception {
  69. TypeReference<Map<String, String>> typeRef = new TypeReference<Map<String, String>>() {};
  70. return OBJECT_MAPPER.readValue(jsonStr, typeRef);
  71. }
  72. }

使用示例

假设你有一个 JSON 字符串,表示一个用户列表: 

String usersJson = "[{\"id\":1,\"name\":\"Alice\"},{\"id\":2,\"name\":\"Bob\"}]";

可以使用上面定义的工具类来将其转换为 List<User>:

  1. import ;
  2. public class User {
  3. private int id;
  4. private String name;
  5. // Getters and setters
  6. }
  7. public class Main {
  8. public static void main(String[] args) {
  9. try {
  10. List<User> users = (usersJson, );
  11. (user -> (()));
  12. } catch (Exception e) {
  13. ();
  14. }
  15. }
  16. }

这个工具类提供了一些基本的方法来帮助你处理 JSON 字符串到 Java 对象的转换,你可以根据需

要扩展更多的方法。 


如果你想使用 Jackson 将 JSON 字符串转换为一个包含泛型值的 CommonResult 类型,你可以通

过以下步骤实现:

定义 CommonResult 类,它应该包含一个泛型字段。

创建一个工具类,使用 JavaType 来构建正确的类型,并使用 ObjectMapper 的 readValue 方法来

完成转换。

下面是一个具体的实现示例:

CommonResult 类定义

首先定义 CommonResult 类,它包含一个泛型 data 字段: 

  1. public class CommonResult<T> {
  2. private boolean success;
  3. private String message;
  4. private T data;
  5. // 构造函数、getter 和 setter
  6. public CommonResult() {}
  7. public CommonResult(boolean success, String message, T data) {
  8. this.success = success;
  9. this.message = message;
  10. this.data = data;
  11. }
  12. public boolean isSuccess() {
  13. return success;
  14. }
  15. public void setSuccess(boolean success) {
  16. this.success = success;
  17. }
  18. public String getMessage() {
  19. return message;
  20. }
  21. public void setMessage(String message) {
  22. this.message = message;
  23. }
  24. public T getData() {
  25. return data;
  26. }
  27. public void setData(T data) {
  28. this.data = data;
  29. }
  30. }

Jackson 类型转换工具类

接下来定义一个工具类,用于转换 JSON 字符串到 CommonResult 类型: 

  1. import ;
  2. import ;
  3. import ;
  4. import ;
  5. import ;
  6. public class JacksonJavaTypeUtils {
  7. private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
  8. /**
  9. * 将 JSON 字符串转换为 CommonResult 类型。
  10. *
  11. * @param jsonStr JSON 字符串
  12. * @param clazz 泛型数据的类型
  13. * @param <T> 泛型类型
  14. * @return CommonResult<T>
  15. * @throws Exception 如果转换失败
  16. */
  17. public static <T> CommonResult<T> convertJsonToCommonResult(String jsonStr, Class<T> clazz) throws Exception {
  18. JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(, clazz);
  19. return OBJECT_MAPPER.readValue(jsonStr, javaType);
  20. }
  21. }

假设你有一个 JSON 字符串,表示一个 CommonResult 对象,其中的数据部分是一个 User 类

型: 

String userJson = "{\"success\":true,\"message\":\"OK\",\"data\":{\"id\":1,\"name\":\"Alice\"}}";
  1. import ;
  2. public class User {
  3. private int id;
  4. private String name;
  5. // Getters and setters
  6. }
  7. public class Main {
  8. public static void main(String[] args) {
  9. try {
  10. CommonResult<User> result = (userJson, );
  11. if (()) {
  12. User user = ();
  13. ("User ID: " + ());
  14. ("User Name: " + ());
  15. } else {
  16. ("Error: " + ());
  17. }
  18. } catch (Exception e) {
  19. ();
  20. }
  21. }
  22. }

在这个示例中,我们定义了一个 User 类,并使用 JacksonJavaTypeUtils 中的

convertJsonToCommonResult 方法来将 JSON 字符串转换为 CommonResult<User> 类型。

确保你的项目中已经包含了 Jackson 库的依赖。如果你使用的是 Maven,可以在 文件中

添加如下依赖: 

  1. <dependency>
  2. <groupId></groupId>
  3. <artifactId>jackson-databind</artifactId>
  4. <version>2.13.4.2</version> <!-- 使用最新版本 -->
  5. </dependency>

为了更好地支持将 JSON 字符串转换为 CommonResult 类型,我们可以进一步完善

JacksonJavaTypeUtils 工具类。下面是一个更新后的版本,它包括了错误处理和一些额外的功

能,例如转换JSON字符串到 CommonResult 的列表。

更新后的JacksonJavaTypeUtils工具类 

  1. import ;
  2. import ;
  3. import ;
  4. import ;
  5. import ;
  6. public class JacksonJavaTypeUtils {
  7. private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
  8. /**
  9. * 将 JSON 字符串转换为 CommonResult 类型。
  10. *
  11. * @param jsonStr JSON 字符串
  12. * @param clazz 泛型数据的类型
  13. * @param <T> 泛型类型
  14. * @return CommonResult<T>
  15. * @throws Exception 如果转换失败
  16. */
  17. public static <T> CommonResult<T> convertJsonToCommonResult(String jsonStr, Class<T> clazz) throws Exception {
  18. JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(, clazz);
  19. return OBJECT_MAPPER.readValue(jsonStr, javaType);
  20. }
  21. /**
  22. * 将 JSON 字符串转换为 CommonResult 的列表。
  23. *
  24. * @param jsonStr JSON 字符串
  25. * @param clazz 泛型数据的类型
  26. * @param <T> 泛型类型
  27. * @return List<CommonResult<T>>
  28. * @throws Exception 如果转换失败
  29. */
  30. public static <T> Collection<CommonResult<T>> convertJsonToListOfCommonResults(String jsonStr, Class<T> clazz) throws Exception {
  31. JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructCollectionType(,
  32. OBJECT_MAPPER.getTypeFactory().constructParametricType(, clazz));
  33. return OBJECT_MAPPER.readValue(jsonStr, javaType);
  34. }
  35. }

假设你有两个 JSON 字符串,分别表示一个 CommonResult 对象和一个 CommonResult 的列表,

其中的数据部分是一个 User 类型: 

  1. String singleUserJson = "{\"success\":true,\"message\":\"OK\",\"data\":{\"id\":1,\"name\":\"Alice\"}}";
  2. 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>>: 

  1. import ;
  2. public class User {
  3. private int id;
  4. private String name;
  5. // Getters and setters
  6. }
  7. public class Main {
  8. public static void main(String[] args) {
  9. try {
  10. // 转换单个 CommonResult
  11. CommonResult<User> singleResult = (singleUserJson, );
  12. if (()) {
  13. User user = ();
  14. ("Single User ID: " + ());
  15. ("Single User Name: " + ());
  16. } else {
  17. ("Single Error: " + ());
  18. }
  19. // 转换 CommonResult 的列表
  20. Collection<CommonResult<User>> resultList = (listUserJson, );
  21. for (CommonResult<User> result : resultList) {
  22. if (()) {
  23. User user = ();
  24. ("List User ID: " + ());
  25. ("List User Name: " + ());
  26. } else {
  27. ("List Error: " + ());
  28. }
  29. }
  30. } catch (Exception e) {
  31. ();
  32. }
  33. }
  34. }

在这个示例中,我们定义了一个 User 类,并使用 JacksonJavaTypeUtils 中的

convertJsonToCommonResult 和 convertJsonToListOfCommonResults 方法来将 JSON 字符串转

换为 CommonResult<User> 和 List<CommonResult<User>> 类型。