java - Json 解析错误 - MismatchedInputException 在 Spring Boot 中期望 LocalDate 的数组或字符串

标签 java spring-boot jackson java-time jsonparser

我有 2 个通过 REST 调用进行通信的微服务。 我有一个名为 Consumer 的实体,它具有各种字段,包括 LocalDate。 当我通过 REST 调用传递该实体时,出现以下异常

Json parse error expected array or string.,nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException

在实体类中,我注释如下

@JsonFormat(pattern="yyyy-MM-dd")
private LocalDate dateOfBirth

在 application.properties 中,我添加了以下行,

spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false

我使用的是 Spring Boot 版本 2.1.2.RELEASE。 在 pom.xml 中,我有 jackson 依赖项。

I have added jackson-databind and jackson-datatype-jsr310,
both versions 2.9.9

我在第一个微服务中使用 Retrofit 作为客户端,通过它我对第二个微服务的 REST ENDPOINT(@RestController) 进行 REST 调用。

但我收到错误 - Json 解析错误 - LocalDate 的 MismatchedInputException。 我还需要补充什么吗?

EDIT-1 以下是生成的 JSON 的片段,

{"consumerId":1,"consumerName":"Harry","dateOfBirth":{"year":1991,"month":3,"day":10},"requestDate":"year":2020,"month":8,"day":31}

EDIT-2 我按照此链接实现, http://lewandowski.io/2016/02/formatting-java-time-with-spring-boot-using-json/

根据@rohit 在评论中的建议,在下面另外添加。

@JsonFormat(pattern="yyyy-MM-dd")
@JsonSerialize(using=LocalDateSerializer.class)
@JsonDeserialize(using=LocalDateDeserializer.class)
private LocalDate dateOfBirth

但是在 JSON 中生成的日期格式仍然没有根据格式更改。

"dateOfBirth":{"year":1991,"month":3,"day":10}

应该是,

"dateOfBirth":"1991-03-10"

不是吗??

SpringBoot主类中定义的bean没有被使用吗,

@Bean
@Primary
public ObjectMapper serializingObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    JavaTimeModule javaTimeModule = new JavaTimeModule();
    javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer());
    javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer());
    objectMapper.registerModule(javaTimeModule);
    return objectMapper;
}

现在我遇到了错误,

Json parse error: text; nested exception is com.fasterxml.jackson.databind.JsonMappingException: text (through reference chain com.model.Consumer["dateOfBirth"])

最佳答案

当我使用 Retrofit 时,

向我的 GsonBuilder 添加了一个 registerTypeAdapter,如下所示,

gsonBuilder.registerTypeAdapter(LocalDate.class, new LocalDateSerializer());
gsonBuilder.registerTypeAdapter(LocalDate.class, new LocalDateDeserializer());

关于java - Json 解析错误 - MismatchedInputException 在 Spring Boot 中期望 LocalDate 的数组或字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63665319/

相关文章:

java - 为什么 getFile 的这个实例可以与 SVNKit 一起使用?

java - "Bean type int could not be found"错误,如何解决?

spring-boot - @DataJpaTest 如何指定要扫描的存储库和实体

spring Rest 动态从序列化中排除对象属性

java - isSubstring递归方法

java - Swing 组件的代码说明

java - Jackson 无法反序列化为 ForeignCollection (Ormlite)

java - 使用 jackson 获取值的 json 路径

java - 我正在尝试使用javamail发送电子邮件,但无法正常工作

java - Spring Boot 测试和 Jackson - 在测试中从上下文设置 (application.yml) 获取 ObjectMapper 的实例,无需开销配置