DateTypeAdapter反序列化基于用户24/12小时的偏好设置而失败。...com.google.gson.JsonSyntaxException:1989年9月19日12:44:27

时间:2018-09-19 09:39:40

标签: java android json date

我是第一次在stackoverflow中发布问题,因此,如果有任何语法错误,对不起。面临一个DateTypeAdapter.deserializeToDate()问题。

我的模型班级是:

 Class User {

    @JsonFormat(pattern ="MMM dd, yyyy HH:mm:ss")

    @JsonSerialize(using = CustomDateAndTimeSerializer.class)

    @JsonDeserialize(using = CustomerDateAndTimeDeserialize.class)

    private Date dateOfBirth;

}

//这是模型类

我有CustomDateAndTimeSerializer类

 public class CustomDateAndTimeSerializer extends JsonSerializer<Date> {
    @Override
    public void serialize(Date date, JsonGenerator jsonGenerator, 
    SerializerProvider serializerProvider) throws IOException {
    SimpleDateFormat formatter = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss");
    formatter.setLenient(false);
    String formattedDate = formatter.format(date);
    jsonGenerator.writeString(formattedDate);
    }
}

具有反序列化类

 public class CustomerDateAndTimeDeserialize extends JsonDeserializer<Date> {

    private SimpleDateFormat dateFormat = new SimpleDateFormat(
            "MMM dd, yyyy HH:mm:ss");

    @Override
    public Date deserialize(JsonParser paramJsonParser,DeserializationContext paramDeserializationContext)
            throws IOException, JsonProcessingException {
        String str = paramJsonParser.getText().trim();
        try {
            //dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
            dateFormat.setLenient(false);
            return dateFormat.parse(str);
        } catch (ParseException e) {
            System.out.println("date error"+e.getCause() +  e.getLocalizedMessage() +e.getMessage());
        }
        return paramDeserializationContext.parseDate(str);
    }
}

在使用我的Android应用程序字体时,dateOfBirth出现问题... enter image description here

引发异常

com.google.gson.JsonSyntaxException: Sep 19, 1989 12:44:27 at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate(DateTypeAdapter.java:74)

0 个答案:

没有答案