JSON以自定义格式序列化日期(无法从String值构造java.util.Date的实例)

时间:2022-04-09 18:05:00
could not read JSON: Can not construct instance of java.util.Date from String 
value '2012-07-21 12:11:12': not a valid representation("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))

passing json request to REST controller method in a POJO class.user should enter only in below datetime format other wise it should throw message.why DateSerializer is not calling?

将json请求传递给POJO类中的REST控制器方法。用户应该只输入以下日期时间格式,否则它应该抛出message.why DateSerializer没有调用?

add(@Valid @RequestBody User user)
{
}

json:

JSON:

{
   "name":"ssss",
   "created_date": "2012-07-21 12:11:12"
}

pojo class variable

pojo类变量

@JsonSerialize(using=DateSerializer.class)
@Column
@NotNull(message="Please enter a date")      
@Temporal(value=TemporalType.TIMESTAMP)
private Date created_date;

public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
    logger.info("serialize:"+value);
    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    logger.info("DateSerializer formatter:"+formatter.format(value));
    jgen.writeString(formatter.format(value));
}

4 个解决方案

#1


7  

I have the same problem, so I write a custom date deserialization with @JsonDeserialize(using=CustomerDateAndTimeDeserialize.class)

我有同样的问题,所以我用@JsonDeserialize编写自定义日期反序列化(using = CustomerDateAndTimeDeserialize.class)

public class CustomerDateAndTimeDeserialize extends JsonDeserializer<Date> {

    private SimpleDateFormat dateFormat = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");

    @Override
    public Date deserialize(JsonParser paramJsonParser,
            DeserializationContext paramDeserializationContext)
            throws IOException, JsonProcessingException {
        String str = paramJsonParser.getText().trim();
        try {
            return dateFormat.parse(str);
        } catch (ParseException e) {
            // Handle exception here
        }
        return paramDeserializationContext.parseDate(str);
    }
}

#2


38  

Annotate your created_date field with the JsonFormat annotation to specify the output format.

使用JsonFormat注释注释created_date字段以指定输出格式。

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")

#3


0  

Yet another way is to have a custom Date object which takes care of its own serialization.

另一种方法是使用自定义Date对象来处理自己的序列化。

While I don't really think extending simple objects like Date, Long, etc. is a good practice, in this particular case it makes the code easily readable, has a single point where the format is defined and is rather more than less compatible with normal Date object.

虽然我并不认为扩展像Date,Long等简单对象是一种很好的做法,但在这种特殊情况下,它使代码易于阅读,只有一个点可以定义格式,而且与普通的Date对象。

public class CustomFormatDate extends Date {

    private DateFormat myDateFormat = ...; // your date format

    public CustomFormatDate() {
        super();
    }

    public CustomFormatDate(long date) {
        super(date);
    }

    public CustomFormatDate(Date date) {
        super(date.getTime());
    }


    @JsonCreator
    public static CustomFormatDate forValue(String value) {
        try {
            return new CustomFormatDate(myDateFormat.parse(value));
        } catch (ParseException e) {
            return null;
        }
    }

    @JsonValue
    public String toValue() {
        return myDateFormat.format(this);
    }

    @Override
    public String toString() {
        return toValue();
    }
}

#4


0  

  1. If you want to bind a JSON string to date, this process is called deserialization, not serialization.
  2. 如果要将JSON字符串绑定到日期,则此过程称为反序列化,而不是序列化。
  3. To bind a JSON string to date, create a custom date deserialization, annotate created_date or its setter with

    要将JSON字符串绑定到日期,请创建自定义日期反序列化,注释created_date或其setter with

    @JsonDeserialize(using=YourCustomDateDeserializer.class)

    @JsonDeserialize(使用= YourCustomDateDeserializer.class)

where you have to implement the method public Date deserialize(...) to tell Jackson how to convert a string to a date.

你必须实现方法public Date deserialize(...)告诉Jackson如何将字符串转换为日期。

Enjoy.

请享用。

#1


7  

I have the same problem, so I write a custom date deserialization with @JsonDeserialize(using=CustomerDateAndTimeDeserialize.class)

我有同样的问题,所以我用@JsonDeserialize编写自定义日期反序列化(using = CustomerDateAndTimeDeserialize.class)

public class CustomerDateAndTimeDeserialize extends JsonDeserializer<Date> {

    private SimpleDateFormat dateFormat = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");

    @Override
    public Date deserialize(JsonParser paramJsonParser,
            DeserializationContext paramDeserializationContext)
            throws IOException, JsonProcessingException {
        String str = paramJsonParser.getText().trim();
        try {
            return dateFormat.parse(str);
        } catch (ParseException e) {
            // Handle exception here
        }
        return paramDeserializationContext.parseDate(str);
    }
}

#2


38  

Annotate your created_date field with the JsonFormat annotation to specify the output format.

使用JsonFormat注释注释created_date字段以指定输出格式。

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")

#3


0  

Yet another way is to have a custom Date object which takes care of its own serialization.

另一种方法是使用自定义Date对象来处理自己的序列化。

While I don't really think extending simple objects like Date, Long, etc. is a good practice, in this particular case it makes the code easily readable, has a single point where the format is defined and is rather more than less compatible with normal Date object.

虽然我并不认为扩展像Date,Long等简单对象是一种很好的做法,但在这种特殊情况下,它使代码易于阅读,只有一个点可以定义格式,而且与普通的Date对象。

public class CustomFormatDate extends Date {

    private DateFormat myDateFormat = ...; // your date format

    public CustomFormatDate() {
        super();
    }

    public CustomFormatDate(long date) {
        super(date);
    }

    public CustomFormatDate(Date date) {
        super(date.getTime());
    }


    @JsonCreator
    public static CustomFormatDate forValue(String value) {
        try {
            return new CustomFormatDate(myDateFormat.parse(value));
        } catch (ParseException e) {
            return null;
        }
    }

    @JsonValue
    public String toValue() {
        return myDateFormat.format(this);
    }

    @Override
    public String toString() {
        return toValue();
    }
}

#4


0  

  1. If you want to bind a JSON string to date, this process is called deserialization, not serialization.
  2. 如果要将JSON字符串绑定到日期,则此过程称为反序列化,而不是序列化。
  3. To bind a JSON string to date, create a custom date deserialization, annotate created_date or its setter with

    要将JSON字符串绑定到日期,请创建自定义日期反序列化,注释created_date或其setter with

    @JsonDeserialize(using=YourCustomDateDeserializer.class)

    @JsonDeserialize(使用= YourCustomDateDeserializer.class)

where you have to implement the method public Date deserialize(...) to tell Jackson how to convert a string to a date.

你必须实现方法public Date deserialize(...)告诉Jackson如何将字符串转换为日期。

Enjoy.

请享用。