什么是杰克逊反序列化相当于@JsonUnwrapped? [英] What's the Jackson deserialization equivalent of @JsonUnwrapped?

查看:493
本文介绍了什么是杰克逊反序列化相当于@JsonUnwrapped?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下课程:

public class Parent {
  public int age;
  @JsonUnwrapped
  public Name name;
}

制作JSON:

{
  "age" : 18,
  "first" : "Joey",
  "last" : "Sixpack"
}

如何将其反序列化回Parent类?我可以使用@JsonCreator

How do I deserialize this back into the Parent class? I could use @JsonCreator

@JsonCreator
public Parent(Map<String,String> jsonMap) {
  age = jsonMap.get("age");
  name = new Name(jsonMap.get("first"), jsonMap.get("last"));
}

但这也有效地添加了 @JsonIgnoreProperties(ignoreUnknown = true)到Parent类,因为所有属性都映射到此处。因此,如果您希望未知的JSON字段引发异常,则必须自己执行此操作。此外,如果地图值可能不是字符串,则必须进行一些手动类型检查和转换。杰克逊有办法自动处理这个案子吗?

But this also effectively adds @JsonIgnoreProperties(ignoreUnknown=true) to the Parent class, as all properties map to here. So if you wanted unknown JSON fields to throw an exception, you'd have to do that yourself. In addition, if the map values could be something other than Strings, you'd have to do some manual type checking and conversion. Is there a way for Jackson to handle this case automatically?

编辑:
我可能会疯了,但实际上这似乎是尽管文档中没有明确提到,但仍然可以工作: http://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonUnwrapped.html

我很确定它以前对我不起作用。尽管如此,当需要自定义逻辑反序列化未包装的多态类型时,建议的@JsonCreator方法可能更受欢迎。

I might be crazy, but this actually appears to work despite never being explicitly mentioned in the documentation: http://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonUnwrapped.html
I was pretty sure it didn't work for me previously. Still, the proposed @JsonCreator approach might be preferred when custom logic is required to deserialize unwrapped polymorphic types.

推荐答案

您可以使用 @JsonCreator 每个字段的 @JsonProperty

You can use @JsonCreator with @JsonProperty for each field:

@JsonCreator
public Parent(@JsonProperty("age") Integer age, @JsonProperty("firstName") String firstName,
        @JsonProperty("lastName") String lastName) {
    this.age = age;
    this.name = new Name(firstName, lastName);
}

在这种情况下,杰克逊会为您进行类型检查和未知字段检查。

Jackson does type checking and unknown field checking for you in this case.

这篇关于什么是杰克逊反序列化相当于@JsonUnwrapped?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆