ObjectMapper

编程入门 行业动态 更新时间:2024-10-25 12:26:46

<a href=https://www.elefans.com/category/jswz/34/1652081.html style=ObjectMapper"/>

ObjectMapper

目录

一、复杂类型反序列化

1.1、背景

1.2、问题解决


一、复杂类型反序列化


1.1、背景

a)例如有 AppResult 对象,如下:

@Data
public class AppResult {private Integer code;private String msg;private Object data;}

b)AppResult 对象中 Object 类型的 data 数据传入一个 User 对象,如下:

@Data
public class User {private Long id;private String username;private String password;}

c)然后将 AppResult 对象通过 ObjectMapper.writeValueAsString 序列化成 JSON 格式.

1.2、问题解决

那么我们该怎么反序列化呢?

一个错误的思路如下:

a)使用 ObjectMapper.readValue() 反序列化成 AppResult 对象.

b)然后他取出 AppResult 中的 data 数据,但由于是 Object 类型,因此需要强制类型转化成 User 对象.

结果就是报错:java.util.LinkedHashMap cannot be cast to User

原因如下:

当使用 ObjectMapper.readValue() 方法将 JSON 字符串反序列化为 AppResult 对象时,如果 AppResult 对象的 data 属性是一个泛型(如 Object ),那么 Jackson 将无法知道这个属性的确切类型,因此会将其反序列化为一个 LinkedHashMap.

解决办法:

我们首先解析整个 JSON 字符串为 AppResult 对象。然后,我们使用 ObjectMapper 的 convertValue 方法将 AppResult 对象中的 data 属性转换为一个 User 对象。这里我们使用了 TypeReference 来指定我们希望得到的是一个 User 类型的对象。

            AppResult result = null;try {result = objectMapper.readValue(userinfo, AppResult.class);} catch (JsonProcessingException e) {throw new RuntimeException(e);}//3.解析出用户信息User user = objectMapper.convertValue(result.getData(), new TypeReference<User>() {});

ObjectMapper 的 convertValue 方法在 Jackson 库中是用来进行对象转换的。这个方法可以将一种 Java 类型转换为另一种 Java 类型。例如,如果你有一个 Map 对象,你可能想要将它转换为一个更具体的对象。convertValue 方法可以帮助你完成这种转换。

更多推荐

ObjectMapper

本文发布于:2023-11-15 14:15:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1601066.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:ObjectMapper

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!