更简洁地说,我建议为此使用两个单独的@JsonSetter注释。下面是一个工作示例。这意味着您的 java 类将只有一个 getter 方法用于该属性,而不是两个。您还可以将不希望的 setter 公开给 Media 的客户端,并以特殊方式处理其中一个 json 密钥。
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSetter;
import com.fasterxml.jackson.databind.ObjectMapper;
@SuppressWarnings("unused")
public class Media {
private Asset asset;
@JsonGetter("asset")
public Asset getAsset() {
return asset;
}
@JsonSetter("asset")
public void setAsset(Asset asset) {
this.asset = asset;
}
@JsonSetter("cover_asset")
private void setMediaAsset(Asset asset) {
if (this.asset == null) {
setAsset(asset);
}
}
private static class Asset {
@JsonProperty("foo")
private String foo;
}
public static void main(String[] args) throws Exception {
String withAsset = "{'asset': {'foo':'bar'}}";
String withCoverAsset = "{'cover_asset': {'foo':'bar'}}";
ObjectMapper mapper = new ObjectMapper();
Media mediaFromAsset = mapper.readValue(withAsset.replace('\'','"'), Media.class);
Media mediaFromCoverAsset = mapper.readValue(withCoverAsset.replace('\'','"'), Media.class);
System.out.println(mediaFromAsset.asset.foo.equals(mediaFromCoverAsset.asset.foo));
}
}