【发布时间】:2019-06-18 13:18:49
【问题描述】:
我有一个Spring 项目,在控制器方法中我有@RequestBody Object obj 作为参数之一。
对象具有Date 字段,其中自定义JSON Serializer 和自定义JSON Deserializer 使用@JsonDeserializer 和@JsonSerializer 以及这两个类实现。
当我向控制器方法Spring 发送请求时,调用Jacksons 反序列化器并将Object 的字符串日期字段反序列化为Date。
当反序列化器反序列化日期字符串并返回 Date 对象时,我希望它根据对象的 format 字段中给出的格式解析字符串(即格式也在输入中给出)并创建 Date相应地反对。如何实现?
class MyObject{
private String format; //field containing the format
private Date currentDate;// this field should get formatted according to the 'format' field value
@JsonSerialize(using = CustomJSONSerializer.class)
public Date getCurrentDate(){
return this.currentDate;
}
@JsonDeserialize(using = CustomJsonDeserializer.class)
public void setCurrentDate(Date currentDate){
this.currentDate=currentDate;
}
}
class CustomJsonDeserializer extends JsonDeserializer<Date> {
@Override
public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
//this format I want it to receive from the input as well i.e from the Object's format named instance variable.
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
try {
return simpleDateFormat.parse(jp.getText());
} catch (ParseException e) {
//catch exception
}
}
我们可以使用JsonParser 或DeserializationContext 来解决这个问题吗?
【问题讨论】:
标签: java json jackson deserialization json-deserialization