正如@Kimble 所说,使用Jackson 2,使用默认格式非常容易;只需JodaModule
在您的ObjectMapper
.
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
对于自定义序列化/反序列化DateTime
,您需要实现自己的StdScalarSerializer
和StdScalarDeserializer
;这很令人费解,但无论如何。
例如,这是一个使用UTC 时区的DateTime
序列化程序:ISODateFormat
public class DateTimeSerializer extends StdScalarSerializer<DateTime> {
public DateTimeSerializer() {
super(DateTime.class);
}
@Override
public void serialize(DateTime dateTime,
JsonGenerator jsonGenerator,
SerializerProvider provider) throws IOException, JsonGenerationException {
String dateTimeAsString = ISODateTimeFormat.withZoneUTC().print(dateTime);
jsonGenerator.writeString(dateTimeAsString);
}
}
以及相应的反序列化器:
public class DateTimeDesrializer extends StdScalarDeserializer<DateTime> {
public DateTimeDesrializer() {
super(DateTime.class);
}
@Override
public DateTime deserialize(JsonParser jsonParser,
DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
try {
JsonToken currentToken = jsonParser.getCurrentToken();
if (currentToken == JsonToken.VALUE_STRING) {
String dateTimeAsString = jsonParser.getText().trim();
return ISODateTimeFormat.withZoneUTC().parseDateTime(dateTimeAsString);
}
} finally {
throw deserializationContext.mappingException(getValueClass());
}
}
然后将它们与一个模块联系在一起:
public class DateTimeModule extends SimpleModule {
public DateTimeModule() {
super();
addSerializer(DateTime.class, new DateTimeSerializer());
addDeserializer(DateTime.class, new DateTimeDeserializer());
}
}
然后在您的ObjectMapper
:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new DateTimeModule());