2018.09.13 更新:
将查询出来的Java对象转换为JSONObject时,报了如下错误
java.lang.IllegalArgumentException at java.sql.Date.getHours JSONException
经过一番折腾,大体知道如何规避这个错误,就是使用JSONConfig转换日期类型
JsonConfig config = new JsonConfig();
config.registerJsonValueProcessor(Date.class,new DateJsonValueProcessor("yyyy-MM-dd"));
JSONObject formJson = JSONObject.fromObject(model,config);
本以为就这样轻松的解决问题,结果报了死循环的错误
JSONException: There is a cycle in the hierarchy!
查资料,知道了当对象存在与其他对象的关联时,如果不在JSONConfig里面排除,就会陷入无休止的循环。比如,学生对象有个teacher属性,就必须把teacher排除。。
config.setExcludes(new String[]{"teacher"});
--------------------------------------------------------------------
2018.08 更新:
做项目遇到一个需求:给一些路径url,要求以树的格式输出到浏览器,前端使用ztree接收ajax请求。
完成这个功能的过程中,接触了JSON的用法,现记录下来。
- 使用的JSON在net.sf.json包下
- JSONObject和JSONArray的使用?
JSONArray firstArray = new JSONArray();
JSONObject firstObject = new JSONObject();
firstObject.put("name", "一级分类");
JSONArray secondArray = new JSONArray();
JSONObject secondObject = new JSONObject();
secondObject.put("name", "二级分类");
secondArray.add(secondObject);
firstObject.element("children", secondArray);
firstArray.add(firstObject);
顺便记录下,以前用到的json对象转java的工具类:fastjson