前端传的"yyyy-MM-dd HH:mm:ss" 格式的字符串 ,后台转换不了:org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: The date should be a string value; nested exception is com.google.gson.JsonParseException: The date should be a string value
后台数据date传到前端 转换成 "yyyy-MM-dd HH:mm:ss" ,但是前端"yyyy-MM-dd HH:mm:ss"传到后端 gson解析不了 。
但是 前端传这种格式就能解析转成date :"2018-08-22T02:44:09.647Z"
应该是你解析的格式没有配好
Date转字符串
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(date);
System.out.print(dateString);
字符串转Date
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
String str = "2017-02-18";
try {
date = format.parse(str);
System.out.print(date);
} catch (ParseException e) {
e.printStackTrace();
}
The date should be a string value, 你传的值有问题,你得看传过来的值啊
应该要先转换为String,再去做日期型格式化的操作
传到后端的完整参数是什么?是不是json没提出来?
用这个
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setDateFormat("yyyy-MM-dd HH:mm:ss")
.create();
根据实际需求实体类配合@Expose 使用
弄了一下午终于解决了
由于用的gson 加了一个配置类
new GsonBuilder()
.registerTypeAdapter(Date.class,new DateAdapter())
.setDateFormat("yyyy-MM-dd HH:mm:ss").serializeNulls().create();
private static class DateAdapter implements JsonSerializer ,JsonDeserializer{
//数据返回时date转成json字符
@Override
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
if (src == null) {
return new JsonPrimitive("");
} else {
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return new JsonPrimitive(formatter.format(src));
}
}
//前端请求是 把json格式日期转成date
@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Date date = null;
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date = formatter.parse(json.getAsString());
}catch (Exception e){
e.printStackTrace();
}
return date;
}
}