【问题标题】:Spring Boot: Prevent Jackson from "reformatting" XMLGregorianCalendar upon JSON serializationSpring Boot:防止 Jackson 在 JSON 序列化时“重新格式化”XMLGregorianCalendar
【发布时间】:2021-03-27 13:01:25
【问题描述】:

我的 Spring Boot 应用程序查询外部 SOAP 服务。从它的 WSDL/XSD 生成类后,这就是类的样子。

如您所见,dateOfBirth 的类型为 XMLGregorianCalendar。 SOAP 响应包含以下格式的出生日期:1991-11-08+01:00

public class Applicant {

    // other properties

    @XmlElement(required = true)
    @XmlSchemaType(name = "date")
    protected XMLGregorianCalendar dateOfBirth;

    // getters & setters
}

Spring 应用程序接收来自 SOAP 服务的响应主体,并将其作为 Jackson 序列化的 JSON“按原样”返回给其调用客户端。问题是,杰克逊似乎将dateOfBirth 序列化为另一种格式。

这是 cilent 最终收到的格式:

{
  "dateOfBirth": "1976-11-12T23:00:00.000+00:00"
}

是否有一些配置或自定义实现我可以使用,这样杰克逊就不会重新格式化这个日期?在最坏的情况下,我可以编写一个映射 SOAP 响应的类,但这听起来很乏味。

【问题讨论】:

    标签: json spring spring-boot jackson


    【解决方案1】:

    尝试像这样配置您的映射器:

    mapper.setDateFormat(new SimpleDateFormat("dd-MM-yyyy+hh:mm"));
    

    应该可以 但是如果你想要更多的控制,你可以使用@JsonFormat 注释:

    public class Applicant {
    
        @XmlElement(required = true)
        @XmlSchemaType(name = "date")
        @JsonFormat( shape = JsonFormat.Shape.STRING, pattern ="dd-MM-yyyy+hh:mm")
        protected XMLGregorianCalendar dateOfBirth;
    }
    

    更多控制:https://www.baeldung.com/jackson-annotations

    来源:https://github.com/FasterXML/jackson-docs

    【讨论】:

    • 问题是,Applicant 类是从外部系统的 WSDL/XSD 和wsimport 生成的,即我无法控制这个类中的注释。
    • 在这种情况下,只需公开一个具有相应设置的 DateFormat 的 ObjectMapper 就可以解决问题,但是该配置将应用于您的应用程序中序列化为 json 的所有日期,如果 wsdl 预计不会更改并且你没有在部署管道中生成源你总是可以在生成的类中添加注释(我知道它不是那么干净,但它是一个快速的解决方案)
    猜你喜欢
    • 2017-10-30
    • 2018-11-07
    • 2016-04-09
    • 2019-04-03
    • 1970-01-01
    • 2017-09-09
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多