Java Date转Json报错解决方案
报错信息为:
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.commons.beanutils.PropertyUtilsBean.invokeMethod(PropertyUtilsBean.java:2155)
at org.apache.commons.beanutils.PropertyUtilsBean.getSimpleProperty(PropertyUtilsBean.java:1323)
at org.apache.commons.beanutils.PropertyUtilsBean.getNestedProperty(PropertyUtilsBean.java:762)
at org.apache.commons.beanutils.PropertyUtilsBean.getProperty(PropertyUtilsBean.java:837)
at org.apache.commons.beanutils.PropertyUtils.getProperty(PropertyUtils.java:426)
at net.sf.json.JSONObject.defaultBeanProcessing(JSONObject.java:749)
... 55 more
Caused by: java.lang.IllegalArgumentException
at java.sql.Date.getHours(Date.java:187)
... 65 more
原因:
java.sql.util.Date类的getHours方法已经被弃用,但是net.sf.json.JSONObject.fromObject(javaObject)进行json序列化的时候仍然调用了这个方法。
这篇博客中描述的很详细:https://segmentfault.com/a/1190000016937108
结局方法:
json-lib有一个配置类JsonConfig,通过JsonConfig可以注册一个字段处理器,通过实现JsonValueProcessor接口,将Date格式化后使用。
加入依赖:
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
实现接口:
@Test
public void testJson(){
Map<String, Object> mp = new ModelMap();
mp.put("server",server.getAll());
JsonConfig config = new JsonConfig();
config.registerJsonValueProcessor(java.sql.Date.class, new JsonValueProcessor() {
private SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
@Override
public Object processArrayValue(Object arg0, JsonConfig arg1) {
return null;
}
@Override
public Object processObjectValue(String arg0, Object arg1, JsonConfig arg2) {
return arg1 == null ? "" : sd.format(arg1);
}
});
JSONObject jsonObject = JSONObject.fromObject(mp);
String msg = jsonObject.toString();
System.out.println(msg);
}
为了更好的明天