JSON 以自定义格式序列化日期(无法从字符串值构造 java.util.Date 的实例) [英] JSON Serializing date in a custom format (Can not construct instance of java.util.Date from String value)
本文介绍了JSON 以自定义格式序列化日期(无法从字符串值构造 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 请求传递给 POJO 类中的 REST 控制器方法.用户应该只输入以下日期时间格式,否则它应该抛出消息.为什么 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 以自定义格式序列化日期(无法从字符串值构造 java.util.Date 的实例)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文