jackson:“(尽管至少存在一个创建者):没有要反序列化的字符串参数构造函数/工厂方法”

ttvkxqim  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(463)

虽然这个问题听起来很简单,但我在一个非常简单的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文件位于类路径上。
我所尝试的:
明确的 @AllArgsConstructor Lombok山注解 Error
int codeInteger code (可为空类型)
移动 Error 班外 Foo (非内部类)

x4shl7ld

x4shl7ld1#

考虑使用@ Builder进行@ JSONSORID注解
https://projectlombok.org/features/experimental/jacksonized
修复json对象的格式错误。”“错误”使用的是对象数组,因此您应该有如下内容:

{
    "errors": [{
        "message": "bla bla bla"
    }]
}

相关问题