首页 > 解决方案 > 是否可以将 JsonFormat 日期时间的某些部分设为可选?

问题描述

我有一个用秒部分定义的字段(即:“ss”),如下所示

@JsonProperty("date")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss z")
private Date date;

是否可以将秒部分设为可选?以便以下日期字符串都可以工作:

我正在考虑类似的事情(但这不起作用......):“yyyy-MM-dd'T'HH:mm[:ss] z”

谢谢。

标签: javajsondatedatetimeformat

解决方案


我得到了答案。

  1. 添加一个客户化的反序列化器类“DateDeserializer.class”
  2. DateDeserializer.class 实现了有和没有第二部分的模式。

附上代码示例:

@JsonDeserialize(using = DateDeserializer.class)
@JsonProperty("date")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss z")




public class DateDeserializer extends StdDeserializer<Date> {

private static final SimpleDateFormat withSeconds = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss z");
private static final SimpleDateFormat withoutSeconds = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm z");

public DateDeserializer() {
    this(null);
}

public DateDeserializer(Class<?> vc) {
    super(vc);
}

@Override
public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    String dateString = p.getText();
    if (dateString.isEmpty()) {
        //handle empty strings however you want,
        //but I am setting the Date objects null
        return null;
    }

    try {
        return withSeconds.parse(dateString);
    } catch (ParseException e) {
        try {
            return withoutSeconds.parse(dateString);
        } catch (ParseException e1) {
            throw new RuntimeException("Unable to parse date", e1);
        }
    }
}
} 

推荐阅读