Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 857
Punter Vicky Avatar asked Dec 29 '15 22:12

Punter Vicky


People also ask

How do you tell Jackson to ignore a field during serialization?

If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.

Does Jackson require serializable?

Jackson actually doesn't need classes to implement Serializable but I'm going to add it anyway. Writing about a serialization framework and not implementing Serializable might seem strange.

How does Jackson serialize date?

It's important to note that Jackson will serialize the Date to a timestamp format by default (number of milliseconds since January 1st, 1970, UTC).


1 Answers

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

like image 162
KSTN Avatar answered Sep 23 '22 02:09

KSTN