如何使用Jackson ObjectMapper将相同的@jsonalias映射到不同的对象字段
在我的DTO类中,可能会有可能具有相同的@jsonalias值的字段,但这似乎与Jackson ObjectMapper不起作用。
看来ObjectMapper仅适用于@jsonalias的首次出现,并且对其余的@jsonalias不起作用,@jsonalias具有相同的值。我试图在下面创建一个示例以供参考,在该示例中,Person类具有具有名称@jsonalias值的两个字段。
代码片段:
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
Map<String, String> values = new HashMap<>();
values.put("name", "TEST NAME");
Person person = new ObjectMapper().convertValue(values, Person.class);
System.out.println("name1: " + person.getName1());
System.out.println("name2: " + person.getName2());
}
static class Person {
@JsonAlias("name")
String name1;
@JsonAlias("name")
String name2;
public String getName1() {
return name1;
}
public void setName1(String name1) {
this.name1 = name1;
}
public String getName2() {
return name2;
}
public void setName2(String name2) {
this.name2 = name2;
}
}
}
输出:
name1: TEST NAME
name2: null
在上述输出中。我期望在同类中为NAME2变量提供“测试名称”。
Jackson ObjectMapper中是否有任何配置可以帮助我实现这一目标?
杰克逊版-Jackson-Databind-2.11.4.jar
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
解决方案1,
@jsongetter
@jsonsetter
指出指向自定义getter \ setter我们可以使用)和 @jsonsetter(“ name”)注释将一个JSON属性值映射到具有处理两个属性
解决方案2,
@jsonalias
的设置器,并使用特定的setter我们可以忽略一个字段,第二个带有别名的标记,并添加一个自定义
setName
setter将一个JSON值映射到几个字段。或者只需在您的原始代码
解决方案3,
@jsonproperty
带有特定setter也像解决方案2一样,而是使用@jsonproperty(“ name”)
更新:
如果您没有修改DTO对象的能力,则自定义求职者可以解决该问题。
将Deserializer应用于DTO对象:
或在
ObjectMapper
上注册Custom DeserializerSolution 1,
@JsonGetter
@JsonSetter
point out to the custom getter\setterWe can use @JsonGetter("name") and @JsonSetter("name") annotations to map one JSON property value to the setter which has handling two properties
Solution 2,
@JsonAlias
with the specific setterWe can ignore one field, the second mark with an alias, and add a custom
setName
setter that maps one JSON value to several fields.Or just add a custom
setName
setter to your original codeSolution 3,
@JsonProperty
with the specific setterThe same like Solution 2, but instead use @JsonProperty("name")
UPDATE:
In case you do not have the ability to modify DTO object, custom deserializer resolve the problem.
Apply deserializer to the DTO object:
OR register custom deserializer on
ObjectMapper