Jackson中的@JsaonAlias和@JsonProperty

1,204 阅读1分钟

JsonAlias

首先看看注解本意

Annotation that can be used to define one or more alternative names for a property, accepted during deserialization as alternative to the official name. Alias information is also exposed during POJO introspection, but has no effect during serialization where primary name is always used.

大致意思为,该注解用来定义某个属性的一个或多个可选的名称,当反序列化时,可以接受不同的名称作为正式名称。但是在序列化时不生效。

所以当json文件中的字段可能存在多种风格或者多种不同的名字时,可以使用此注解来兼容。

public class AliasEntity {
    private String name;

    @JsonAlias({"home_town", "homeTown"})
    private String homeTown;
}

该类中的homeTown字段可以接受"homeTown"和"home_town"两种key。

{
  "name": "Xiaoming",
  "home_town": "henan"
}

{
  "name": "Xiaoming",
  "homeTown": "henan"
}

以上两种写法,都可以成功序列化。

序列化时需要使用@JsonProperty来指定

如:

    @JsonProperty("home_town")
    @JsonAlias({"home_town", "homeTown"})
    private String homeTown;

序列化时,始终输出为"home_town"。