Jackson:“(虽然至少有一个 Creator 存在):没有字符串参数 constructor/factory 反序列化方法”
Jackson: "(although at least one Creator exists): no String-argument constructor/factory method to deserialize"
虽然这个问题听起来很简单,但我在一个非常简单的 bean 上也遇到了这个异常:
@Data
public class Foo {
private List<Error> errors;
@Data
public static class Error {
private int code;
private String message;
}
}
JSON:
{
"errors": [
"message": "bla bla bla"
]
}
异常:com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of "org.example.app.Foo$Error" (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('message')
应用程序:
@SpringBootApplication
public class Application {
public static void main(String[] args) throws Exception {
ApplicationContext context = SpringApplication.run(Application.class, args);
ObjectMapper objectMapper = context.getBean(ObjectMapper.class);
Resource resource = new ClassPathResource("request.json");
try (InputStream stream = resource.getInputStream()) {
Foo foo = objectMapper.readValue(stream, Foo.class);
System.out.println(foo);
}
}
}
JSON 文件位于 class 路径。
我尝试过的:
- 在
Error
class 上显式 @AllArgsConstructor
Lombok 注释
- 从
int code
切换到 Integer code
(可空类型)
- 将
Error
class 移出 Foo
(非内部 class)
考虑使用 @Jacksonized 注释和 @Builder 根据
https://projectlombok.org/features/experimental/Jacksonized
修复您的 json 对象以及它的格式错误。 “错误”正在使用对象数组,所以你应该有这样的东西:
{
"errors": [{
"message": "bla bla bla"
}]
}
虽然这个问题听起来很简单,但我在一个非常简单的 bean 上也遇到了这个异常:
@Data
public class Foo {
private List<Error> errors;
@Data
public static class Error {
private int code;
private String message;
}
}
JSON:
{
"errors": [
"message": "bla bla bla"
]
}
异常:com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of "org.example.app.Foo$Error" (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('message')
应用程序:
@SpringBootApplication
public class Application {
public static void main(String[] args) throws Exception {
ApplicationContext context = SpringApplication.run(Application.class, args);
ObjectMapper objectMapper = context.getBean(ObjectMapper.class);
Resource resource = new ClassPathResource("request.json");
try (InputStream stream = resource.getInputStream()) {
Foo foo = objectMapper.readValue(stream, Foo.class);
System.out.println(foo);
}
}
}
JSON 文件位于 class 路径。
我尝试过的:
- 在
Error
class 上显式 - 从
int code
切换到Integer code
(可空类型) - 将
Error
class 移出Foo
(非内部 class)
@AllArgsConstructor
Lombok 注释
考虑使用 @Jacksonized 注释和 @Builder 根据
https://projectlombok.org/features/experimental/Jacksonized
修复您的 json 对象以及它的格式错误。 “错误”正在使用对象数组,所以你应该有这样的东西:
{
"errors": [{
"message": "bla bla bla"
}]
}