JSON parse error : Can not construct instance of java.util.Date from String value
将json串转化为java对象:
-
json串
{ "id" : "1", "name" : "测试商品", "addTime" : "2017/1/05 11:23:09" }
-
java 类 (省略get/set方法)
public class Item { private int id ; private String name ; private Date addTime ; }
-
解决方法
- 自定义json串解析器
public class OptimizedDateDeserializer extends JsonDeserializer<Date> { @Override public Date deserialize( JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); String date = jsonParser.getText(); try { return format.parse(date); } catch (ParseException e) { System.out.println("OptimizedDateDeserializer - 日期格式错误"); } return null; } }
- 指定解析器
@JsonDeserialize(using = OptimizedDateDeserializer.class) private Date addTime ;
- 自定义json串解析器
网友评论