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;
}
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.
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.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With