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"))
将json请求传递给POJO class.user中的REST控制器方法应该只以低于datetime的格式输入,否则它应该抛出message.why DateSerializer没有调用?
add(@Valid @RequestBody User user)
{
}
json:
{
"name":"ssss",
"created_date": "2012-07-21 12:11:12"
}
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));
}
发布于 2014-11-19 10:27:05
我也有同样的问题,所以我用@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);
}
}
发布于 2014-11-26 00:12:07
使用JsonFormat
注释为created_date
字段添加注释,以指定输出格式。
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = TimeZone.getDefault(), locale = Locale.getDefault())
请注意,如果不是基于服务器使用的语言环境和TimeZone,则可能需要传入不同的语言环境和uses。
你可以在the docs上找到更多信息。
发布于 2015-03-26 19:17:51
另一种方法是拥有一个自定义的Date对象,它负责自己的序列化。
虽然我真的不认为扩展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();
}
}
https://stackoverflow.com/questions/17655532
复制相似问题