Jackson 序列化忽略时区

Pun*_*cky 5 java spring jackson spring-boot

我使用以下代码序列化从外部服务获得的响应,并将 json 响应作为我的服务的一部分返回。但是,当外部服务返回时间值和时区 (10:30:00.000-05.00) 时,jackson 会将其转换为 15:30:00。如何忽略时区值?

public interface DateFormatMixin {

    @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="HH:mm:ss")
    public XMLGregorianCalendar getStartTime();
    @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="HH:mm:ss")
    public XMLGregorianCalendar getEndTime();
}


public ObjectMapper objectMapper() {
    com.fasterxml.jackson.databind.ObjectMapper responseMapper = new com.fasterxml.jackson.databind.ObjectMapper();
    responseMapper.addMixIn(Time.class, DateFormatMixin.class);
    return responseMapper;
}
Run Code Online (Sandbox Code Playgroud)

Man*_*kus 4

您可以创建自定义解串器

public class CustomJsonTimeDeserializerWithoutTimeZone extends JsonDeserializer<Time>{

    @Override
    public Time deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        DateFormat format = new SimpleDateFormat("hh:mm:ss.SSS");
        Time time = null;
        try{
            Date dt = format.parse("10:30:00.000-05.00".substring(0,12)); // remove incorrect timezone format
            return new Time(dt.getTime());
        }catch (ParseException e){
            e.printStackTrace();
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

告诉杰克逊使用您的自定义解串器

public class Model{
    @JsonDeserialize(using = CustomJsonTimeDeserializerWithoutTimeZone.class)
    private Time time;
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

ObjectMapper mapper = new ObjectMapper();

String jsonString = ...// jsonString retrieve from external service
Model model = mapper.readValue(jsonString, Model.class);
Run Code Online (Sandbox Code Playgroud)

您可以使用 Jackson 自定义序列化为您的服务响应添加时区信息