简体   繁体   English

无法从 String 值实例化 [简单类型,类 java.time.LocalDate] 类型的值

[英]Can not instantiate value of type [simple type, class java.time.LocalDate] from String value

I have a class like this:我有一个这样的课程:

@Data
@NoArgsConstructor(force = true)
@AllArgsConstructor(staticName = "of")
public class BusinessPeriodDTO {
    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
    LocalDate startDate;
    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
    LocalDate endDate;
}

And I used this class inside another class, let's call it PurchaseOrder我在另一个类中使用了这个类,我们称之为PurchaseOrder

@Entity
@Data
@NoArgsConstructor(access = AccessLevel.PROTECTED, force = true)
public class PurchaseOrder {
    @EmbeddedId
    PurchaseOrderID id;

    @Embedded
    BusinessPeriod rentalPeriod;

    public static PurchaseOrder of(PurchaseOrderID id, BusinessPeriod period) {
        PurchaseOrder po = new PurchaseOrder();
        po.id = id;

        po.rentalPeriod = period;

        return po;
    }

And I'm trying to populate a purchaseOrder record using jakson and this JSON:我正在尝试使用 jakson 和这个 JSON 填充 purchaseOrder 记录:

 {
     "_class": "com.rentit.sales.domain.model.PurchaseOrder",
     "id": 1,
     "rentalPeriod": {
         "startDate": "2016-10-10",
         "endDate": "2016-12-12"
     }
 }

But I have faced with an error:但是我遇到了一个错误:

java.lang.RuntimeException: com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class java.time.LocalDate] from String value ('2016-10-10'); java.lang.RuntimeException:com.fasterxml.jackson.databind.JsonMappingException:无法从字符串值('2016-10-10')实例化[简单类型,类java.time.LocalDate]类型的值;

I am sure jakson and popularization works correctly.我确信 jakson 和大众化工作正常。

Include in your pom.xml:包括在你的 pom.xml 中:

<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-jsr310</artifactId>
  <version>2.9.6</version>
</dependency>

Then in your BusinessPeriodDTO.java import LocalDateDeserializer as follows:然后在您的BusinessPeriodDTO.java导入LocalDateDeserializer如下:

import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;

And finally, always in your BusinessPeriodDTO.java file, annotate the interested dates like this:最后,始终在您的BusinessPeriodDTO.java文件中,像这样注释感兴趣的日期:

@JsonDeserialize(using = LocalDateDeserializer.class)
LocalDate startDate;
@JsonDeserialize(using = LocalDateDeserializer.class)
LocalDate endDate;

Old question but I recently had to answer it for myself.老问题,但我最近不得不自己回答。 There are different solutions (as commented by rapasoft, see for example here ).有不同的解决方案(如 rapasoft 所评论的,请参见此处的示例)。 The quick solution I used involves adding a setDate(String) method for deserialization.我使用的快速解决方案涉及添加一个用于反序列化的setDate(String)方法。 It might not be the prettiest solution, but it works without updating other classes.它可能不是最漂亮的解决方案,但它无需更新其他类即可工作。 Below a runnable class to demonstrate:下面是一个可运行的类来演示:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonFormat.Shape;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

/**
 * Demonstrate Java 8 date/time (de)serialization for JSON with Jackson databind.
 * Requires {@code com.fasterxml.jackson.core:jackson-databind:2.8.5} 
 * and {@code com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.8.5} 
 */
public class JdateDto {

    /** The pattern as specified by {@link java.text.SimpleDateFormat} */
    public static final String ISO_LOCAL_DATE_PATTERN = "yyyy-MM-dd";

    /* Used when serializing isoLocalDate. */
    @JsonFormat(shape = Shape.STRING, pattern = ISO_LOCAL_DATE_PATTERN)
    private LocalDate isoLocalDate;

    public LocalDate getIsoLocalDate() {
        return isoLocalDate;
    }

    /* Used when deserializing isoLocalDate. */
    public void setIsoLocalDate(String date) {
        setIsoLocalDate(LocalDate.parse(date, DateTimeFormatter.ISO_LOCAL_DATE));
    }

    public void setIsoLocalDate(LocalDate isoDate) {
        this.isoLocalDate = isoDate;
    }

    public static void main(String[] args) {

        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.registerModule(new JavaTimeModule());
            JdateDto dto = new JdateDto();
            dto.setIsoLocalDate(LocalDate.now());
            String json = mapper.writeValueAsString(dto);
            System.out.println(json);
            JdateDto dto2 = mapper.readValue(json, JdateDto.class);
            if (dto.getIsoLocalDate().equals(dto2.getIsoLocalDate())) {
                System.out.println("Dates match.");
            } else {
                System.out.println("Dates do not match!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法实例化类型 [简单类型,类 java.time.LocalDate 的值 - Can not instantiate value of type [simple type, class java.time.LocalDate 无法将“java.lang.String”类型的值转换为所需类型“java.time.LocalDate” - Cannot convert value of type 'java.lang.String' to required type 'java.time.LocalDate' 无法将 [java.lang.String] 类型的属性值转换为所需类型 [java.time.LocalDate] - Failed to convert property value of type [java.lang.String] to required type [java.time.LocalDate] 无法将“java.lang.String”类型的值转换为所需的“java.time.LocalDate”类型; - Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDate'; 无法反序列化“java.time.LocalDate”类型的值 - Cannot deserialize value of type `java.time.LocalDate` setCellValue(String value) throws java: cannot access java.time.LocalDate class file for java.time.LocalDate not found - setCellValue(String value) throws java: cannot access java.time.LocalDate class file for java.time.LocalDate not found 将属性“创建”反序列化时出现问题(预期类型:[简单类型,类java.time.LocalDate] - Problem deserializing property 'created' (expected type: [simple type, class java.time.LocalDate] Spring Boot 2.1.5 无法将 java.lang.String 类型的属性值转换为所需类型 java.time.LocalDate - Spring Boot 2.1.5 Failed to convert property value of type java.lang.String to required type java.time.LocalDate JHipster 生成的文件无法将类型“java.lang.String”的属性值转换为所需类型“java.time.LocalDate” - JHipster generated file failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDate' 将 java.time.LocalDate 转换为 java.util.Date 类型 - Convert java.time.LocalDate into java.util.Date type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM