搜索
首页Java反序列化 LocalDateTime 时出现问题:Jackson InvalidFormatException

php小编子墨为您带来关于Java反序列化LocalDateTime时出现问题的解决方法。在使用Jackson库进行反序列化时,有时会遇到InvalidFormatException的异常,特别是在处理LocalDateTime类型时更为常见。本文将详细介绍该问题的原因和解决方案,帮助您顺利解决这一常见的反序列化异常。

问题内容

我在 spring boot 应用程序中反序列化 localdatetime 时遇到问题。下面是相关代码。

前端:

update(lancamento: lancamento): promise<lancamento> {
      const headers = new httpheaders()
        .set('authorization', this.chave)
        .set('content-type', 'application/json');

        this.conversordedata([lancamento]);

        return firstvaluefrom(this.http.put<any>(`${this.url}/${lancamento.codigo}`,
      lancamento, { headers }));
    }

    findbycode(codigo: number): promise<lancamento> {
      const headers = new httpheaders()
        .set('authorization', this.chave);

      return this.http.get(`${this.url}/${codigo}`,
        { headers })
        .topromise()
        .then((response: any) => {
          const lancamento = response as lancamento;

          this.conversordedata([lancamento]);

          return lancamento;
        })
        .catch((error: any) => {
          console.error('erro ao buscar lançamento por código: ', error);
          throw error;
        });
    }

//se os atributos forem do tipo date
conversordedata(lancamentos: lancamento[]){
  for(const lancamento of lancamentos){
    if(lancamento.datavencimento && isvalid(lancamento.datavencimento)){
      lancamento.datavencimento = new date(format(lancamento.datavencimento, 'dd/mm/yyyy'));
    }
    if(lancamento.datapagamento && isvalid(lancamento.datapagamento)){
      lancamento.datapagamento = new date(format(lancamento.datapagamento, 'dd/mm/yyyy'));
    }

  }
}

后端:lancamento 类:

package com.algaworks.algamoney_api.domain.model;

import com.fasterxml.jackson.annotation.jsonformat;
import jakarta.persistence.*;
import jakarta.validation.constraints.notnull;
import org.springframework.format.annotation.datetimeformat;

import java.math.bigdecimal;
import java.time.localdate;
import java.time.localdatetime;
import java.util.objects;

@entity
@table(name = "lancamento")
public class lancamento {

    @id
    @generatedvalue(strategy = generationtype.identity)
    private integer codigo;

    @notnull
    private string descricao;

    @column(name = "data_vencimento")
    @jsonformat(pattern = "dd/mm/yyyy")
    private localdatetime datavencimento;

    @column(name = "data_pagamento")
    @jsonformat(pattern = "dd/mm/yyyy")
    private localdatetime datapagamento;

    @notnull
    private bigdecimal valor;
    private string observacao;

    @notnull
    @enumerated(enumtype.string)
    private tipolancamento tipo;

    @notnull
    @manytoone // vários lançamentos podem estar em uma categoria
    @joincolumn(name = "codigo_categoria")
    private categoria categoria;

    @notnull
    @manytoone
    @joincolumn(name = "codigo_pessoa")
    private pessoa pessoa;

    public integer getcodigo() {
        return codigo;
    }

    public void setcodigo(integer codigo) {
        this.codigo = codigo;
    }

    public string getdescricao() {
        return descricao;
    }

    public void setdescricao(string descricao) {
        this.descricao = descricao;
    }

    public localdatetime getdatavencimento() {
        return datavencimento;
    }

    public void setdatavencimento(localdatetime datavencimento) {
        this.datavencimento = datavencimento;
    }

    public localdatetime getdatapagamento() {
        return datapagamento;
    }

    public void setdatapagamento(localdatetime datapagamento) {
        this.datapagamento = datapagamento;
    }

    public bigdecimal getvalor() {
        return valor;
    }

    public void setvalor(bigdecimal valor) {
        this.valor = valor;
    }

    public string getobservacao() {
        return observacao;
    }

    public void setobservacao(string observacao) {
        this.observacao = observacao;
    }

    public tipolancamento gettipo() {
        return tipo;
    }

    public void settipo(tipolancamento tipo) {
        this.tipo = tipo;
    }

    public categoria getcategoria() {
        return categoria;
    }

    public void setcategoria(categoria categoria) {
        this.categoria = categoria;
    }

    public pessoa getpessoa() {
        return pessoa;
    }

    public void setpessoa(pessoa pessoa) {
        this.pessoa = pessoa;
    }

    @override
    public boolean equals(object o) {
        if (this == o) return true;
        if (o == null || getclass() != o.getclass()) return false;
        lancamento that = (lancamento) o;
        return codigo.equals(that.codigo);
    }

    @override
    public int hashcode() {
        return objects.hash(codigo);
    }
}

resumolancamento 类:

package com.algaworks.algamoney_api.repository.projection;

import com.algaworks.algamoney_api.domain.model.tipolancamento;

import java.math.bigdecimal;
import java.time.localdate;
import java.time.localdatetime;

/**
 * 7.1. implementando projeção de lançamento*/

public class resumolancamento {

    private integer codigo;
    private string descricao;
    private localdatetime datavencimento;
    private localdatetime datapagamento;
    private bigdecimal valor;
    private tipolancamento tipo;
    private string categoria;
    private string pessoa;

    public resumolancamento(integer codigo, string descricao, localdatetime datavencimento, localdatetime datapagamento, bigdecimal valor, tipolancamento tipo, string categoria, string pessoa) {
        this.codigo = codigo;
        this.descricao = descricao;
        this.datavencimento = datavencimento;
        this.datapagamento = datapagamento;
        this.valor = valor;
        this.tipo = tipo;
        this.categoria = categoria;
        this.pessoa = pessoa;
    }

    public integer getcodigo() {
        return codigo;
    }

    public void setcodigo(integer codigo) {
        this.codigo = codigo;
    }

    public string getdescricao() {
        return descricao;
    }

    public void setdescricao(string descricao) {
        this.descricao = descricao;
    }

    public localdatetime getdatavencimento() {
        return datavencimento;
    }

    public void setdatavencimento(localdatetime datavencimento) {
        this.datavencimento = datavencimento;
    }

    public localdatetime getdatapagamento() {
        return datapagamento;
    }

    public void setdatapagamento(localdatetime datapagamento) {
        this.datapagamento = datapagamento;
    }

    public bigdecimal getvalor() {
        return valor;
    }

    public void setvalor(bigdecimal valor) {
        this.valor = valor;
    }

    public tipolancamento gettipo() {
        return tipo;
    }

    public void settipo(tipolancamento tipo) {
        this.tipo = tipo;
    }

    public string getcategoria() {
        return categoria;
    }

    public void setcategoria(string categoria) {
        this.categoria = categoria;
    }

    public string getpessoa() {
        return pessoa;
    }

    public void setpessoa(string pessoa) {
        this.pessoa = pessoa;
    }
}

问题:

com.fasterxml.jackson.databind.exc.invalidformatexception:无法从字符串“10/01/2024”反序列化 java.time.localdatetime 类型的值:无法反序列化 java.time.localdatetime:(java.time.format .datetimeparseexception)无法解析文本“10/01/2024”:无法从 temporalaccessor 获取 localdatetime:{},iso 解析为 java.time.format.parsed 类型的 2024-01-10 在[来源:(org.springframework.util.streamutils$nonclosinginputstream);行:1,列:63](通过参考链:com.algaworks.algamoney_api.domain.model.lancamento[“datavencimento”])

lancamentos的console.log()中,属性“datavencimento”和“datapagamento”的格式为“dd/mm/yyyy”。

我怀疑反序列化期间存在日期格式问题。尽管更新了前端和后端代码,问题仍然存在。我相信问题出在客户身上,我不知道。

  1. 在 spring boot 应用程序中从字符串反序列化 localdatetime 时,如何修复 invalidformatexception?
  2. 正确的 localdatetime 序列化和反序列化是否需要特定的配置或调整?

如有任何指导或建议,我们将不胜感激。谢谢!

我用 dataconverter() 方法做了所有事情,但仍然没有成功。

conversorDeData(lancamentos: Lancamento[]){
  for(const lancamento of lancamentos){
    if(lancamento.dataVencimento && isValid(lancamento.dataVencimento)){
      lancamento.dataVencimento = new Date(format(lancamento.dataVencimento, 'dd/MM/yyyy'));
    }
    if(lancamento.dataPagamento && isValid(lancamento.dataPagamento)){
      lancamento.dataPagamento = new Date(format(lancamento.dataPagamento, 'dd/MM/yyyy'));
    }

  }
}

解决方法

要解决此问题,您可以执行以下操作之一:

选项 1:调整 json 日期格式 更改 json 负载中的日期格式以匹配模式“yyyy-mm-ddthh:mm:ss”或与 localdatetime 直接兼容的任何格式。例如:

{
  "codigo": 1,
  "descricao": "sample description",
  "datavencimento": "2024-01-10t00:00:00",
  "datapagamento": "2024-01-10t00:00:00",
  "valor": 100.0,
  "observacao": "sample observation",
  "tipo": "sample_type",
  "categoria": {
    "codigo": 1
  },
  "pessoa": {
    "codigo": 1
  }
}

选项2:使用@jsondeserialize指定自定义反序列化格式 您可以使用 @jsondeserialize 注释 lancamento 类中的 localdatetime 字段,以指定自定义反序列化格式。例如:

import com.fasterxml.jackson.databind.annotation.jsondeserialize;
import com.fasterxml.jackson.datatype.jsr310.deser.localdatetimedeserializer;
// other imports...

@entity
@table(name = "lancamento")
public class lancamento {
    // ... other fields

    @column(name = "data_vencimento")
    @jsondeserialize(using = localdatetimedeserializer.class)
    private localdatetime datavencimento;

    @column(name = "data_pagamento")
    @jsondeserialize(using = localdatetimedeserializer.class)
    private localdatetime datapagamento;

    // ... other methods
}

请记住调整 json 负载中的反序列化格式或日期格式,以确保它们正确对齐。选择最适合您的要求和编码实践的方法。

选项 3:出现此问题的原因是 java 中的 localdatetime 没有针对包含日期和时间组件的模式“dd/mm/yyyy”的直接格式化程序。如果您只对日期组件感兴趣,您可能需要将这些字段的类型更改为 localdate。

//...

@Column(name = "data_vencimento")
@JsonFormat(pattern = "dd/MM/yyyy")
private LocalDate dataVencimento;

@Column(name = "data_pagamento")
@JsonFormat(pattern = "dd/MM/yyyy")
private LocalDate dataPagamento;

//...

public LocalDate getDataVencimento() {
    return dataVencimento;
}

public void setDataVencimento(LocalDate dataVencimento) {
    this.dataVencimento = dataVencimento;
}

public LocalDate getDataPagamento() {
    return dataPagamento;
}

public void setDataPagamento(LocalDate dataPagamento) {
    this.dataPagamento = dataPagamento;
}

以上是反序列化 LocalDateTime 时出现问题:Jackson InvalidFormatException的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:stackoverflow。如有侵权,请联系admin@php.cn删除

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器