问题描述
我有一个有字段的 POJO:
I have a POJO which has a field:
public class Media {
private Asset asset;
}
将 json 响应解析为此资产 POJO 时,一切正常.但是,此资产附带的密钥略有不同.它可以是:
Everything works perfectly when parsing a json response into this asset POJO. but however there is a slight difference with the key this asset comes with. It can either be:
@JsonProperty("cover_asset")
或
@JsonProperty("asset")
有没有办法注释 POJO 以识别这种情况并将其反序列化为同一字段.它们不可能出现在同一个响应中.
Is there a way to annotate the POJO to recognize this case and de-serialize into the same field. Its not possible for both of them to appear in the same response.
推荐答案
嗯,因为只有反序列化是你关心的,@JsonAlias
在2.9
中引入是完美的对于这种情况.你可以这样做:
Well, as only deserialization is your concern, @JsonAlias
introduced in 2.9
is perfect for this situation. You can do something like this:
@JsonAlias({"cover_asset", "asset"})
private Asset asset;
可用于定义一个或多个替代名称的注解对于属性,在反序列化期间接受作为替代官方名字.POJO期间也暴露别名信息内省,但在主要的序列化期间没有影响始终使用名称.
注意:如果您正在使用它们,请确保更新所有相关的依赖项(annotations
、core
、databind
).在没有其他人的情况下只更新 annotations
会给我带来运行时错误.
Note: Make sure you update all related dependencies(annotations
, core
, databind
) if you are using them. Updating just annotations
without others threw me runtime error.
这篇关于JSON Jackson 将不同的键解析为同一字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!