我尝试在应用程序的客户端序列化一个对象(来自 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",“注册”]
这是序列化对象的函数:
public static String convertObjectToJson(Object object) throws IOException {
ObjectWriter objectWriter = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = objectWriter.writeValueAsString(object);
return json;
}
问题出在哪里?
最佳答案
Jackson 默认情况下会将 java 枚举表示为简单字符串,因此您无法反序列化该对象
看看这里,它可能会有所帮助:http://www.baeldung.com/jackson-serialize-enums
关于java - 无法使用 jackson @JsonTypeInfo 注释将对象反序列化为其原始类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34096545/