JSON Jackson 将不同的键解析为同一字段 [英] JSON Jackson parse different keys into same field

查看:26
本文介绍了JSON Jackson 将不同的键解析为同一字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有字段的 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.

推荐答案

嗯,因为只有反序列化是你关心的,@JsonAlias2.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;

@JsonAlias 文档:

可用于定义一个或多个替代名称的注解对于属性,在反序列化期间接受作为替代官方名字.POJO期间也暴露别名信息内省,但在主要的序列化期间没有影响始终使用名称.

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.

注意:如果您正在使用它们,请确保更新所有相关的依赖项(annotationscoredatabind).在没有其他人的情况下只更新 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 将不同的键解析为同一字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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