Heim > Java > Hauptteil

Problem beim Deserialisieren von LocalDateTime: Jackson InvalidFormatException

王林
Freigeben: 2024-02-22 13:58:06
nach vorne
359 Leute haben es durchsucht

Der PHP-Editor Zimo bietet Ihnen Lösungen für Probleme, wenn Java LocalDateTime deserialisiert. Wenn Sie die Jackson-Bibliothek zur Deserialisierung verwenden, tritt manchmal eine InvalidFormatException-Ausnahme auf, insbesondere wenn es um den Typ LocalDateTime geht. In diesem Artikel werden die Ursache und Lösung dieses Problems ausführlich vorgestellt, um Ihnen bei der erfolgreichen Lösung dieser häufigen Deserialisierungsausnahme zu helfen.

Frageninhalt

Ich habe ein Problem beim Deserialisieren von localdatetime in einer Spring-Boot-Anwendung. Unten finden Sie den entsprechenden Code.

Frontend:

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'));
    }

  }
}
Nach dem Login kopieren

Backend: lancamento Klasse:

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);
    }
}
Nach dem Login kopieren

resumolancamento Kategorie:

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;
    }
}
Nach dem Login kopieren

Frage:

com.fasterxml.jackson.databind.exc.invalidformatException: Deserialisieren von der Zeichenfolge „01.10.2024“ nicht möglich. Wert vom Typ java.time.localdatetime: Deserialisieren nicht möglich java.time.localdatetime: (java.time.format .datetimeparseeception ) Nicht möglich Text „01.10.2024“ analysieren: Localdatetime kann nicht von temporalaccessor abgerufen werden: {}, ISO analysiert als 10.01.2024 vom Typ java.time.format.parsed In [Quelle: (org.springframework.util.streamutils$nonclosinginputstream); Zeile: 1, Spalte: 63] (über Referenzkette: com.algaworks.algamoney_api.domain.model.lancamento["datavencimento"])

In console.log() von Lancamentos ist das Format der Attribute „datavencimento“ und „datapagamento“ „TT/MM/JJJJ“.

Ich vermute, dass es während der Deserialisierung ein Problem mit dem Datumsformat gibt. Trotz Aktualisierung des Frontend- und Backend-Codes besteht das Problem weiterhin. Ich glaube, das Problem liegt beim Kunden, ich weiß es nicht.

  1. Wie behebe ich eine ungültige Formatausnahme beim Deserialisieren von localdatetime aus einem String in der Spring-Boot-Anwendung?
  2. Erfordert die korrekte Serialisierung und Deserialisierung von localdatetime eine spezielle Konfiguration oder Optimierung?

Jede Anleitung oder Anregung wäre sehr dankbar. Danke!

Ich habe alles mit der Methode dataconverter() gemacht, aber immer noch kein Erfolg.

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'));
    }

  }
}
Nach dem Login kopieren

Workaround

Um dieses Problem zu beheben, können Sie einen der folgenden Schritte ausführen:

Option 1: JSON-Datumsformat anpassen Ändern Sie das Datumsformat in der JSON-Nutzlast so, dass es dem Muster „jjjj-mm-ttthh:mm:ss“ oder einem beliebigen Format entspricht, das direkt mit localdatetime kompatibel ist. Zum Beispiel:

{
  "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
  }
}
Nach dem Login kopieren

Option 2: Verwenden Sie @jsondeserialize, um ein benutzerdefiniertes Deserialisierungsformat anzugeben Sie können das Feld „localdatetime“ in der Klasse „lancamento“ mit @jsondeserialize annotieren, um ein benutzerdefiniertes Deserialisierungsformat anzugeben. Zum Beispiel:

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
}
Nach dem Login kopieren

Denken Sie daran, das Deserialisierungsformat oder das Datumsformat in der JSON-Nutzlast anzupassen, um sicherzustellen, dass sie richtig ausgerichtet sind. Wählen Sie die Methode, die Ihren Anforderungen und Codierungspraktiken am besten entspricht.

Option 3: Dieses Problem tritt auf, weil localdatetime in Java keinen direkten Formatierer für das Muster „tt/mm/jjjj“ hat, das Datums- und Uhrzeitkomponenten enthält. Wenn Sie nur an der Datumskomponente interessiert sind, müssen Sie möglicherweise den Typ dieser Felder in „localdate“ ändern.

//...

@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;
}
Nach dem Login kopieren

Das obige ist der detaillierte Inhalt vonProblem beim Deserialisieren von LocalDateTime: Jackson InvalidFormatException. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:stackoverflow.com
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!