我使用以下代码来序列化从外部服务获得的响应,并作为我的服务的一部分返回json响应。但是,当外部服务返回带有时区(10:30:00.000-05.00)的时间值时,杰克逊会将其转换为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; }
您可以创建自定义解串器
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(); } } }
告诉杰克逊使用您的自定义解串器
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自定义序列化为服务响应添加时区信息