目錄
問題內容
解決方法
首頁 Java 反序列化 LocalDateTime 時出現問題:Jackson InvalidFormatException

反序列化 LocalDateTime 時出現問題:Jackson InvalidFormatException

Feb 22, 2024 pm 01:58 PM

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中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡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脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆樹的耳語 - 如何解鎖抓鉤
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1666
14
CakePHP 教程
1425
52
Laravel 教程
1325
25
PHP教程
1273
29
C# 教程
1252
24