本站资源收集于互联网,不提供软件存储服务,每天免费更新优质的软件以及学习资源!

反序列化LocalDateTime时出现问题:JacksonInvalidFormatException

网络教程 app 1℃

反序列化LocalDateTime时出现问题JacksonInvalidFormatException

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) =&gt; { const lancamento = response as lancamento; this.conversordedata([lancamento]); return lancamento; }) .catch((error: any) =&gt; { console.error(‘erro ao buscar lançamento por código: ‘, error); throw error; }); }//se os atributos forem do tipo dateconversordedata(lancamentos: lancamento[]){ for(const lancamento of lancamentos){ if(lancamento.datavencimento &amp;&amp; isvalid(lancamento.datavencimento)){lancamento.datavencimento = new date(format(lancamento.datavencimento, ‘dd/mm/yyyy’)); } if(lancamento.datapagamento &amp;&amp; isvalid(lancamento.datapagamento)){lancamento.datapagamento = new date(format(lancamento.datapagamento, ‘dd/mm/yyyy’)); } }}</lancamento></any></lancamento>

后端:lancamento 类:

package .algaworks.algamoney_api.domain.model;import .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 .algaworks.algamoney_api.repository.projection;import .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; }}

问题:

.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](通过参考链:.algaworks.algamoney_api.domain.model.lancamento[“datavencimento”])

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

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

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

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

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

conversorDeData(lancamentos: Lancamento[]){ for(const lancamento of lancamentos){ if(lancamento.dataVencimento &amp;&amp; isValid(lancamento.dataVencimento)){lancamento.dataVencimento = new Date(format(lancamento.dataVencimento, ‘dd/MM/yyyy’)); } if(lancamento.dataPagamento &amp;&amp; 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 .fasterxml.jackson.databind.annotation.jsondeserialize;import .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的详细内容,更多请关注范的资源库其它相关文章!

转载请注明:范的资源库 » 反序列化LocalDateTime时出现问题:JacksonInvalidFormatException

喜欢 (0)