【问题标题】:How to parse Input Object Date fields with format given in the object field itself如何使用对象字段本身中给定的格式解析输入对象日期字段
【发布时间】: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
    }
}

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

【问题讨论】:

    标签: java json jackson deserialization json-deserialization


    【解决方案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 {
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多