我有一个POJO,它有一个字段:

public class Media {
 private Asset asset;
}

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")

or

  @JsonProperty("asset")

有没有办法注释POJO以识别这种情况并反序列化到同一字段.它们不可能同时出现在同一react 中.

推荐答案

嗯,因为您只关心反序列化,所以2.9中引入的@JsonAlias非常适合这种情况.您可以这样做:

@JsonAlias({"cover_asset", "asset"})
private Asset asset;

@JsonAlias docs:

可用于定义一个或多个备选名称的注释

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相关问答推荐

Jolt转换,如果任何字段为空,则将对象值设置为空

服务器不返回JSON

我可以使用JQ来缩小数组中的json对象的范围吗?

kotlinx-serialization:如何将具有不同类型对象的JsonArray转换为同一个Class

如何创建可由Gin序列化到json的排序键值映射?

解析JSON说函数parse_json不存在?

Azure数据工厂-WEB活动输出赢得';t返回JSON

为什么 Django Rest API 序列化器没有正确序列化多对多字段

PostgreSQL:删除 JSONB 数组中每个元素的特定键

Jolt规范:将嵌套数组中的null元素移除

JOLT 在 struct 体中间添加一个 JSON 字段

将 json 文件转换为 json 对象会打乱对象的顺序

如何在循环中传递列表(会话(字符串属性))以在 Gatling Scala 中创建批量 Json 请求

使用 System.Text.Json 序列化记录成员

SyntaxError:Object.parse(本机)AngularJS中的意外标记o

python,将Json写入文件

反序列化大型 json 对象的 JsonMaxLength 异常

使用 gson 反序列化对象的特定 JSON 字段

如何创建 JSON 对象 Node.js

带有 Jackson 的不可变 Lombok 注释类