在spring中,反序列化带或不带零的日期(yyyy-m-d),但总是用零序列化它们(yyyy-mm-dd)?

x4shl7ld  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(231)

我有一个spring应用程序

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.11.0</version>
</dependency>

我可以从前端接收带有日期字段的json对象,可以有前导零,也可以没有前导零(1991-2-3或1991-02-03)。我知道,用 yyyy-M-d 用于反序列化输入:

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class MyDto implements Serializable{

     //other fields...

     @JsonDeserialize(using = LocalDateDeserializer.class)
     @JsonSerialize(using = LocalDateSerializer.class)
     @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-M-d")
     LocalDate date;

}

问题是它总是返回没有填充零的日期,例如。 1991-2-3 . 有没有一种方法可以让它接受任何一种模式,但总是序列化以包含零,例如。 1991-02-03 ?

6qftjkof

6qftjkof1#

我发现可以实现自定义反序列化程序来代替使用 @JsonFormat ,使用 DateTimeFormatter :

public class CustomLocalDateDeserializer extends JsonDeserializer<LocalDate> {

    private final static Logger log = LoggerFactory.getLogger(CustomLocalDateDeserializer.class);

    @Override
    public LocalDate deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException{

        String dateAsString = jsonParser.getText();

        if(dateAsString.isEmpty()) return null;

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-d");
        LocalDate date = LocalDate.parse(dateAsString, formatter);

        return date;

    }

}

public class CustomLocalDateSerializer extends JsonSerializer<LocalDate>{

    @Override
    public void serialize(LocalDate value, JsonGenerator generator, SerializerProvider provider) throws IOException{
        if (value == null) {
            generator.writeNull();
        } else {
            generator.writeString(value.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        }
    }

}

然后,只需在注解中使用自定义反序列化程序

@JsonDeserialize(using = CustomLocalDateDeserializer.class)
@JsonSerialize(using = CustomLocalDateSerializer.class)
private LocalDate aLocalDate;

相关问题