杰克逊序列化忽略时区 [英] Jackson Serialization Ignore Timezone

查看:139
本文介绍了杰克逊序列化忽略时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use the below code for serializing the response that get from an external service an return a json response back as part of my service. However when the external service return a time value along with timezone (10:30:00.000-05.00) , jackson is converting it to 15:30:00. How can I ignore the timezone value?

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


推荐答案

您可以创建自定义反序列化器

You can create custom deserializer

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

}

告诉杰克逊使用自定义反序列化器

tell jackson to use your custom deserializer

public class Model{
    @JsonDeserialize(using = CustomJsonTimeDeserializerWithoutTimeZone.class)
    private Time time;
}

并像这样使用:

ObjectMapper mapper = new ObjectMapper();

String jsonString = ...// jsonString retrieve from external service
Model model = mapper.readValue(jsonString, Model.class);

您可以使用Jackson Custom Serialization为您的服务回复添加时区信息

You can use Jackson Custom Serialization to add timezone information for your service response

这篇关于杰克逊序列化忽略时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆