[英]Mapping a json string to an object with jackson will throw MismatchedInputException
我有一个简单的课程
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;
}
}
有了杰克逊,我试图将字符串映射到这个对象
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();
}
但它引发了以下异常
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]
我试图在我的AuthenticationToken中将该属性注释为@JsonProperty,但这也导致了这个异常。
使用@JsonCreator
注释类构造@JsonCreator
标记注释,可用于将构造函数和工厂方法定义为用于实例化关联类的新实例的注释。
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会指望一个“ 空 ”构造函数,并会通过为每个字段提供的getter和setter自动填充Object。
因此删除构造函数的参数已经解决了您的问题:
public class AuthenticationToken {
public String token;
public AuthenticationToken() {}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
如果你想保持现有的构造函数,你也可以添加一个额外的空构造函数。 测试了两个测试用例的选项,都可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.