import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CustomDateSerializationExample {
public static class DateSerializer extends JsonSerializer<Date> {
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
@Override
public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
String formattedDate = DATE_FORMAT.format(value);
gen.writeString(formattedDate);
}
}
public static class DateDeserializer extends JsonDeserializer<Date> {
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
@Override
public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String dateString = p.getText();
try {
return DATE_FORMAT.parse(dateString);
} catch (Exception e) {
throw new IOException("Failed to parse date: " + dateString, e);
}
}
}
public static class Person {
private String name;
private Date birthDate;
// 省略构造函数和getter/setter方法
}
public static void main(String[] args) throws Exception {
SimpleModule module = new SimpleModule();
module.addSerializer(Date.class, new DateSerializer());
module.addDeserializer(Date.class, new DateDeserializer());
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(module);
// 序列化示例
Person person = new Person("John Doe", new SimpleDateFormat("yyyy-MM-dd").parse("2000-01-01"));
String json = objectMapper.writeValueAsString(person);
System.out.println(json); // 输出结果:{"name":"John Doe","birthDate":"2000-01-01"}
// 反序列化示例
String jsonInput = "{\"name\":\"Jane Smith\",\"birthDate\":\"1990-12-31\"}";
Person deserializedPerson = objectMapper.readValue(jsonInput, Person.class);
System.out.println(deserializedPerson.getBirthDate()); // 输出结果:Sat Dec 31 00:00:00 GMT 1990
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.