use*_*115 27 json spring-mvc jackson fasterxml
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"))
Run Code Online (Sandbox Code Playgroud)
将json请求传递给POJO类中的REST控制器方法.用户应该只输入以下日期时间格式,否则它应该抛出message.why DateSerializer没有调用?
add(@Valid @RequestBody User user)
{
}
Run Code Online (Sandbox Code Playgroud)
JSON:
{
"name":"ssss",
"created_date": "2012-07-21 12:11:12"
}
Run Code Online (Sandbox Code Playgroud)
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));
}
Run Code Online (Sandbox Code Playgroud)
Spl*_*tar 51
使用注释注释您的created_date字段JsonFormat以指定输出格式.
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = TimeZone.getDefault(), locale = Locale.getDefault())
Run Code Online (Sandbox Code Playgroud)
请注意,如果它们应基于服务器使用的内容以外的其他内容,则可能需要传入不同的Locale和TimeZone.
您可以在文档中找到更多信息.
小智 17
我有同样的问题,所以我写了一个自定义日期反序列化 @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);
}
}
Run Code Online (Sandbox Code Playgroud)