Cannot deserialize value of type LocalDateTime from String

huangapple go评论82阅读模式
英文:

Cannot deserialize value of type LocalDateTime from String

问题

我有以下的 DTOEntity

public class PaymentDto {

    private String provider;

    private Duration timeDifferenceDate;

    public PaymentDto() {
        // Empty for framework
    }

    public PaymentDto(Payment payment) {
        this.provider = payment.getProvider();
        this.setRegistrationDate(payment.getRegistrationDate());
    }

    public Duration getRegistrationDate() {
        return timeDifferenceDate;
    }

    public void setRegistrationDate(LocalDateTime registrationDate) {
        LocalDateTime now = LocalDateTime.now();
        Duration duration = Duration.between(now, registrationDate);
        this.timeDifferenceDate = duration;
    }

}
public class Payment {

    private LocalDateTime registrationDate;

    public Payment() {
        // Empty for framework
    }

但是当它从 Payment 转换为 PaymentDto 时,我在JSON解码方面遇到问题,特别是从 LocalDateTime 转换为 Duration 的过程。有什么想法吗?

    @Override
    public List<PaymentDto> readAll() {
        return this.paymentPersistence.readAll().stream()
                .map(PaymentDto::new).collect(Collectors.toList());
    }
org.springframework.core.codec.DecodingException: JSON decoding error: 无法从字符串“PT-1.015005S”反序列化为类型`java.time.LocalDateTime`:无法将文本“PT-1.015005S”解析为索引0处的java.time.LocalDateTime:(java.time.format.DateTimeParseException);嵌套异常是com.fasterxml.jackson.databind.exc.InvalidFormatException:无法从字符串“PT-1.015005S”反序列化为类型`java.time.LocalDateTime`:无法将文本“PT-1.015005S”解析为索引0处的java.time.LocalDateTime:(java.time.format.DateTimeParseException) Text 'PT-1.015005S' could not be parsed at index 0
 at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: com.user.rest.dtos.PaymentDto["registrationDate"])

    at org.springframework.http.codec.json.AbstractJackson2Decoder.processException(AbstractJackson2Decoder.java:215)
    Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: 
Error has been observed at the following site(s):
    |_ checkpoint ⇢ Body from GET http://localhost:61072/payments [DefaultClientResponse]
Stack trace:
        at org.springframework.http.codec.json.AbstractJackson2Decoder.processException(AbstractJackson2Decoder.java:215)

顺便说一句,谢谢。 😉

英文:

I have the following DTO and Entity:

public class PaymentDto {

    private String provider;

    private Duration timeDifferenceDate;

    public PaymentDto() {
        // Empty for framework
    }

    public PaymentDto(Payment payment) {
        this.provider = payment.getProvider();
        this.setRegistrationDate(payment.getRegistrationDate());
    }

    public Duration getRegistrationDate() {
        return timeDifferenceDate;
    }

    public void setRegistrationDate(LocalDateTime registrationDate) {
        LocalDateTime now = LocalDateTime.now();
        Duration duration = Duration.between(now, registrationDate);
        this.timeDifferenceDate = duration;
    }

}
public class Payment {

    private LocalDateTime registrationDate;

    public Payment() {
        // Empty for framework
    }

But when it converts from Payment to PaymentDto I have problems with JSON decoding, specifically with the conversion from LocalDateTime to Duration. Some idea?

    @Override
    public List&lt;PaymentDto&gt; readAll() {
        return this.paymentPersistence.readAll().stream()
                .map(PaymentDto::new).collect(Collectors.toList());
    }
org.springframework.core.codec.DecodingException: JSON decoding error: Cannot deserialize value of type `java.time.LocalDateTime` from String &quot;PT-1.015005S&quot;: Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text &#39;PT-1.015005S&#39; could not be parsed at index 0; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDateTime` from String &quot;PT-1.015005S&quot;: Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text &#39;PT-1.015005S&#39; could not be parsed at index 0
 at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: com.user.rest.dtos.PaymentDto[&quot;registrationDate&quot;])

	at org.springframework.http.codec.json.AbstractJackson2Decoder.processException(AbstractJackson2Decoder.java:215)
	Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: 
Error has been observed at the following site(s):
	|_ checkpoint ⇢ Body from GET http://localhost:61072/payments [DefaultClientResponse]
Stack trace:
		at org.springframework.http.codec.json.AbstractJackson2Decoder.processException(AbstractJackson2Decoder.java:215)

Thanks by the way. Cannot deserialize value of type LocalDateTime from String

答案1

得分: 2

LocalDateTime 无法转换为 Duration,反之亦然。除了在它们的层次结构中都实现了 Serializable(当然还有 Object)之外,它们没有任何共同点。

private LocalDateTime registrationDate;

替换为

private Duration registrationDate;

或者创建一个新的类型为 Duration 的实例变量。

英文:

LocalDateTime can not be converted to Duration and vice versa. There is nothing common, except Serializable (and of course Object), in their hierarchies.

Replace

private LocalDateTime registrationDate;

with

private Duration registrationDate;

or create a new instance variable of type, Duration.

答案2

得分: 2

如@Arvind Kumar Avinash在上面提到的,您需要在setterPaymentDto::setRegistrationDate中提供适当类型的Duration

另外,如果您从返回LocalDateTime字段的实体填充DTO,则还应修改“conversion”构造函数。此外,在计算持续时间时,应首先放置registrationDate,以避免“负”持续时间(较早的时间点首先出现)。

public PaymentDto(Payment payment) {
    this.provider = payment.getProvider();
    this.setRegistrationDate(Duration.between(
        payment.getRegistrationDate(),  // 较早的“开始”日期应该在前面
        LocalDateTime.now()
    ));
}

public void setRegistrationDate(Duration timeDifference) 
    this.timeDifferenceDate = timeDifference;
}
英文:

As @Arvind Kumar Avinash mentioned above, you need to provide appropriate type Duration in the setter PaymentDto::setRegistrationDate.

Also you should modify the "conversion" constructor if you populate a DTO from an entity which returns a LocalDateTime field. Also, when calculating the duration, you should place registrationDate first to avoid "negative" duration (earlier instant in time comes first).

public PaymentDto(Payment payment) {
    this.provider = payment.getProvider();
    this.setRegistrationDate(Duration.between(
        payment.getRegistrationDate(),  // older &quot;start&quot; date should go first
        LocalDateTime.now()
    ));
}

public void setRegistrationDate(Duration timeDifference) 
    this.timeDifferenceDate = timeDifference;
}

huangapple
  • 本文由 发表于 2020年10月24日 01:36:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/64504830.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定