【问题标题】:How i can force JSON dates to not accept integer in java我如何强制 JSON 日期不接受 java 中的整数
【发布时间】:2021-02-12 17:37:08
【问题描述】:

我如何通过 Java 强制 JSON 日期使用特定模式并且不接受整数,例如:

{ “生日”:1 }

不应被接受。

我试过了

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") 私人 LocalDate 生日;

但仍接受数字。

【问题讨论】:

    标签: java json rest


    【解决方案1】:

    首先创建一个类自定义localDate反序列化器

    公共类 LocalDateDserializer 扩展 StdDeserializer {

    private final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    
    public LocalDateDserializer() {
        this(null);
    }
    
    public LocalDateDserializer(final Class<?> vc) {
        super(vc);
    }
    
    @Override
    public LocalDate deserialize(final JsonParser jsonparser, final DeserializationContext context)
            throws IOException, JsonProcessingException {
        final String date = jsonparser.getText();
        try {
            return formatter.parse(date).toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        } catch (final ParseException e) {
            throw new RuntimeException(e);
        }
    }
    

    }

    使用注解 @JsonDeserialize(使用 = LocalDateDserializer.class) 私人 LocalDate 生日;

    【讨论】:

      猜你喜欢
      • 2018-08-15
      • 1970-01-01
      • 2017-09-14
      • 1970-01-01
      • 2015-11-16
      • 1970-01-01
      • 2012-06-29
      • 1970-01-01
      • 2012-03-09
      相关资源
      最近更新 更多