写代码的时候去数据库查询,返回的数据是map里嵌套list的格式,需要转换成JSON格式返回到页面上,然后遇到一个比较奇怪的报错:
net.sf.json.JSONException: java.lang.reflect.InvocationTargetException
这个报错本身很简单,就是JSON转换错误,但是我按照代码里返回值的结构自己写了测试类进行转换却没有报错
测试类如下:
public class ListToJSON {
public static void main(String[] args) {
Map a = new HashMap();
a.put("name", "xiaoming");
a.put("sex", "male");
a.put("grade", "3");
Map b = new HashMap();
b.put("name", "xiaohua");
b.put("sex", "female");
b.put("grade", "3");
List list = new ArrayList();
list.add(a);
list.add(b);
Map c = new HashMap();
c.put("identity", "student");
c.put("infomation", list);
System.out.println(c);
//JSONObject result = (JSONObject)JSON.toJSON(c);
JSONObject result=JSONObject.fromObject(c);
System.out.println(result.toString());
}
}
后来百度了一下,才明白原因,我查数据库的返回值里有date类型的数据,java.sql.date会转换成java.util.date,这种转换为JSON就会报错
select a.result_comparison as resultComparison,
a.apply_date as applyDate,//此处为日期格式,返回转JSON就会报错
a.interviewee_name as intervieweeName
from visit_appointment_info a
where a.visit_cardno = #visitCardNo#
and a.visit_name = #visitName#
and a.apply_date >= current_date;
解决方式:在mybatis中将日期先改为字符串再返回,就可以了
select a.result_comparison as resultComparison,
to_char(a.apply_date, 'yyyy-mm-dd') as applyDate,
a.interviewee_name as intervieweeName
from visit_appointment_info a
where a.visit_cardno = #visitCardNo#
and a.visit_name = #visitName#
and a.apply_date >= current_date;