我已经在我的项目中使用 FasterXML/Jackson-Databind 一段时间了,一切都很好,直到我发现这篇 文章 并开始使用这种方法在没有 @JsonProperty 注释的情况下反序列化对象。
问题是,当我有一个采用多个参数的构造函数并使用 @JsonCreator 注释装饰此构造函数时,Jackson 抛出以下错误:
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException:
Argument #0 of constructor [constructor for com.eliti.model.Cruiser, annotations: {interface com.fasterxml.jackson.annotation.JsonCreator=@com.fasterxml.jackson.annotation.JsonCreator(mode=DEFAULT)}] has no property name annotation; must have name when multiple-parameter constructor annotated as Creator
at [Source: {
"class" : "com.eliti.model.Cruiser",
"inventor" : "afoaisf",
"type" : "MeansTransport",
"capacity" : 123,
"maxSpeed" : 100
}; line: 1, column: 1]
我创建了一个 小项目 来说明这个问题,我要反序列化的类是这个:
public class Cruise extends WaterVehicle {
private Integer maxSpeed;
@JsonCreator
public Cruise(String name, Integer maxSpeed) {
super(name);
System.out.println("Cruise.Cruise");
this.maxSpeed = maxSpeed;
}
public Integer getMaxSpeed() {
return maxSpeed;
}
public void setMaxSpeed(Integer maxSpeed) {
this.maxSpeed = maxSpeed;
}
}
反序列化的代码是这样的:
public class Test {
public static void main(String[] args) throws IOException {
Cruise cruise = new Cruise("asd", 100);
cruise.setMaxSpeed(100);
cruise.setCapacity(123);
cruise.setInventor("afoaisf");
ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
mapper.registerModule(new ParameterNamesModule(JsonCreator.Mode.PROPERTIES));
String cruiseJson = mapper.writeValueAsString(cruise);
System.out.println(cruiseJson);
System.out.println(mapper.readValue(cruiseJson, Cruise.class));
}
我已经尝试删除 @JsonCreator,但如果我这样做,则会抛出以下异常:
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.eliti.model.Cruise: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?)
at [Source: {
"class" : "com.eliti.model.Cruise",
"inventor" : "afoaisf",
"type" : "MeansTransport",
"capacity" : 123,
"maxSpeed" : 100
}; line: 3, column: 3]
我试图发出“mvn clean install”,但问题仍然存在。
为了包含一些额外的信息,我已经彻底研究了这个问题(GitHub 问题、博客文章、StackOverflow 问答)。这是我一直在做的一些调试/调查:
调查 1
生成的字节码上的 javap -v 给我这个:
MethodParameters:
Name Flags
name
maxSpeed
在谈论构造函数时,我猜想实际上是为 javac 编译器设置了 -parameters 标志。
调查 2
如果我创建一个带有单个参数的构造函数,该对象将被初始化,但我想/需要使用多参数构造函数。
调查 3
如果我在每个字段上使用注释 @JsonProperty 它也能正常工作,但对于我的原始项目来说,它的开销太大,因为我在构造函数中有很多字段(而且很难用注释重构代码)。
剩下的问题是: 如何让 Jackson 在没有注释的情况下使用多参数构造函数?
原文由 pedrostanaka 发布,翻译遵循 CC BY-SA 4.0 许可协议
需要添加注解
@JsonProperty
指定创建对象时需要传递给构造函数的json属性名称。编辑
我刚刚使用下面的代码进行了测试,它对我有用
它产生以下输出
确保 pom 文件中有 compilerArgs。