Hen*_*nri 10 java spring json lombok deserialization
尽管这个问题听起来很简单,但我在一个非常简单的 bean 上也遇到了这个异常:
@Data
public class Foo {
private List<Error> errors;
@Data
public static class Error {
private int code;
private String message;
}
}
Run Code Online (Sandbox Code Playgroud)
JSON:
{
"errors": [
"message": "bla bla bla"
]
}
Run Code Online (Sandbox Code Playgroud)
例外情况: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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
JSON 文件驻留在类路径中。
我尝试过的:
@AllArgsConstructorLombok 注释Errorint code到Integer code(可空类型)Error类移出Foo(非内部类)考虑将@Jacksonized注释与@Builder一起使用
https://projectlombok.org/features/experimental/Jacksonized
修复格式错误的 json 对象。“错误”正在使用对象数组,因此您应该具有以下内容:
{
"errors": [{
"message": "bla bla bla"
}]
}
Run Code Online (Sandbox Code Playgroud)