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

How to parse Input Object Date fields with format given in the object field itself

我有一个 Spring 项目,在控制器方法中我将 @RequestBody Object obj 作为参数之一。 对象具有 Date 字段,其中自定义 JSON Serializer 和自定义 JSON Deserializer 使用 @JsonDeserializer@JsonSerializer 以及两个 类.

实现

当我向控制器方法发送请求时 Spring 调用 Jacksons 反序列化器并将对象的字符串日期字段反序列化为 Date

当反序列化器反序列化日期字符串和 return 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 来解决这个问题吗?

您需要为整个 MyObject class 实施 deserialiser/serialiser 才能访问所有必填字段。请参阅以下示例:

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 {

同样,您可以实现并注册序列化器。