如何使用对象字段本身给定的格式来解析输入对象日期字段

时间:2019-06-18 13:18:49

标签: java json jackson deserialization json-deserialization

我有一个Spring项目,在控制器方法中,我有@RequestBody Object obj作为参数之一。 对象具有Date字段,这些字段具有使用JSON SerializerJSON 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
    }
}

我们可以使用JsonParserDeserializationContext来解决此问题吗?

1 个答案:

答案 0 :(得分:1)

您需要为整个MyObject类实现反序列化器/序列化器,才能访问所有必填字段。参见以下示例:

public class MyObjectJsonDeserializer extends JsonDeserializer<MyObject> {
    @Override
    public MyObject deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        ObjectNode root = p.readValueAsTree();
        String format = root.get("format").asText();

        MyObject result = new MyObject();
        result.setFormat(format);

        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        try {
            result.setCurrentDate(dateFormat.parse(root.get("currentDate").asText()));
        } catch (ParseException e) {
            throw new JsonParseException(p, e.getMessage(), e);
        }

        return result;
    }
}

您可以使用它:

@JsonDeserialize(using = MyObjectJsonDeserializer.class)
public class MyObject {

类似地,您可以实现和注册序列化器。