简体   繁体   中英

Jackson Serialization Ignore Timezone

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

and use it like this:

ObjectMapper mapper = new ObjectMapper();

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

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

You can create deserializer as below:

public Calendar deserialize(JsonParser jsonParser, DeserializationContext context)
        throws IOException, JsonProcessingException {
    DateFormat formatter = new SimpleDateFormat(("yyyy-MM-dd'T'HH:mm:ss.SSS"));
    String date = jsonParser.getText();
    try {
        Calendar cal = Calendar.getInstance();
        cal.setTime(formatter.parse(date));
        return cal;
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM