[英]Mapping a json string to an object with jackson will throw MismatchedInputException
I have a simple class 我有一个简单的课程
public class AuthenticationToken {
public String token;
public AuthenticationToken(String token) {
this.token = token;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
With jackson I am trying to map an string to this object like this 有了杰克逊,我试图将字符串映射到这个对象
private String input = "{\"token\":\"adf\"}";
@Test
public void whenJsonString_ThenCreateAuthenticationObject() throws IOException {
ObjectMapper jsonMapper = new ObjectMapper();
AuthenticationToken tokenObject = jsonMapper.readValue(input, AuthenticationToken.class);
assertThat(tokenObject).isNotNull();
}
But it throws the following exception 但它引发了以下异常
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `foo.AuthenticationToken` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: (String)"{"token":"adf"}"; line: 1, column: 2]
I tried to annotate the property in my AuthenticationToken as a @JsonProperty but this also resulted in in this exception. 我试图在我的AuthenticationToken中将该属性注释为@JsonProperty,但这也导致了这个异常。
Annotate the class constructor with @JsonCreator
使用@JsonCreator
注释类构造@JsonCreator
Marker annotation that can be used to define constructors and factory methods as one to use for instantiating new instances of the associated class. 标记注释,可用于将构造函数和工厂方法定义为用于实例化关联类的新实例的注释。
public class AuthenticationToken {
public String token;
@JsonCreator
public AuthenticationToken(@JsonProperty("token") final String token) {
this.token = token;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
Jackson will by default expect an " empty " constructor and will automatically fill your Object by the getters and setters that are provided for each field. 默认情况下,Jackson会指望一个“ 空 ”构造函数,并会通过为每个字段提供的getter和setter自动填充Object。
So removing the arguments of your constructor will already solve your problem: 因此删除构造函数的参数已经解决了您的问题:
public class AuthenticationToken {
public String token;
public AuthenticationToken() {}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
You could also just add an additional empty constructor if you want to keep your current one as it is. 如果你想保持现有的构造函数,你也可以添加一个额外的空构造函数。 Tested both options for your Test Case, both work fine. 测试了两个测试用例的选项,都可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.