JSON以自定义格式序列化日期(无法从String值构造java.util.Date的实例) [英] JSON Serializing date in a custom format (Can not construct instance of java.util.Date from String value)
本文介绍了JSON以自定义格式序列化日期(无法从String值构造java.util.Date的实例)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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请求传递给REST控制器方法在POJO class.user应该只输入以下日期时间格式,否则它应该抛出message.why DateSerializer没有调用?
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?
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));
}
推荐答案
我遇到同样的问题,所以我写了一个自定义日期反序列化
与 @JsonDeserialize(using = CustomerDateAndTimeDeserialize.class)
I have the same problem, so I write a custom date deserialization
with @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);
}
}
这篇关于JSON以自定义格式序列化日期(无法从String值构造java.util.Date的实例)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文