【问题标题】:can't deserialize an Object to its original Type using jackson @JsonTypeInfo annotation无法使用jackson @JsonTypeInfo 注释将对象反序列化为其原始类型
【发布时间】:2016-03-09 20:53:07
【问题描述】:

我正在尝试在我的应用程序的客户端序列化一个对象(来自 Enum ),并在另一端(服务器端)使用 jackson 将其反序列化为相同的对象。我在客户端有这个枚举:

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@type")
public enum Request{
    Signup,
    Login
}

使用jackson的@jsonTypeInfo注解。

在服务器端我这样做是为了反序列化对象:

ObjectMapper mapper = new ObjectMapper();
    final JsonNode jsonNode;
    jsonNode = mapper.readTree(json);  //json is the return String from the convertObjectToJson(Request.Signup);

    //i get the error on this line
    String type = jsonNode.get("@type").asText();

正如我在上面的代码中评论的那样,我在 jsonNode.get("@type").asText() 上得到 NullException,而 json 是:[ "Request", "Signup" ]

这是序列化对象的函数:

public static String convertObjectToJson(Object object) throws IOException {
        ObjectWriter objectWriter = new ObjectMapper().writer().withDefaultPrettyPrinter();
        String json = objectWriter.writeValueAsString(object);
        return json;
    }

问题出在哪里?

【问题讨论】:

    标签: java json serialization enums jackson


    【解决方案1】:

    Jackson 默认将 java 枚举表示为简单的字符串,因此您无法反序列化对象

    看看这里,它会有所帮助:http://www.baeldung.com/jackson-serialize-enums

    【讨论】:

      猜你喜欢
      • 2013-10-14
      • 2020-04-11
      • 2022-12-19
      • 2021-05-20
      • 1970-01-01
      • 2021-10-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-18
      相关资源
      最近更新 更多