net.sf.json.JSON的一般使用说明

1.对pojo和字符创进行解析

注意:net.sf.json.JSON是根据pojo里面的get方法来转json对象的,如果你需要几个连载一起的属性,只需要写

public String getName({

return region+subarea+province ;

})

就多一个name属性的值,而无需重新定义属性

  1. public class Test {
  2. public static void main(String[] args) {
  3. // JavaBean对象转json字符串
  4. Student stu1 = new Student("lwc", "111111");
  5. JSONObject jsonObject = JSONObject.fromObject(stu1);
  6. System.out.println(jsonObject);
  7. // json字符串转JavaBean
  8. String jsondata = "{"password":"111111","username":"lwc"}";
  9. JSONObject jsonObject1 = JSONObject.fromObject(jsondata);
  10. Student stu2 = (Student) JSONObject.toBean(jsonObject1, Student.class);
  11. System.out.println(stu2);
  12. }
  13. }
  14. /*
  15. 打印结果:
  16. {"password":"111111","username":"lwc"}
  17. 用户: lwc 密码:111111
  18. */

不需要json解析的数据:

JsonConfig jsonConfig = new JsonConfig;

jsonConfig.setexcludes(new String[]{"currentPage","totalPage","detchedcriteria"})

2.对list进行解析


  1. public class Test {
  2. public static void main(String[] args) {
  3. // List转json字符串
  4. List list = new ArrayList();
  5. list.add(new Student("lwc", "111111"));
  6. list.add(new Student("nxj", "222222"));
  7. JSONArray jsonArray = JSONArray.fromObject(list);
  8. System.out.println(jsonArray);
  9. // json字符串转List
  10. List list1 = new ArrayList();
  11. String jsondata = "[{"password":"111111","username":"lwc"},{"password":"222222","username":"nxj"}]";
  12. JSONArray jsonArray1 = JSONArray.fromObject(jsondata);
  13. for (int i = 0; i < jsonArray1.size(); i++) {
  14. JSONObject jsonObject2 = jsonArray1.getJSONObject(i);
  15. Student stu2 = (Student) JSONObject.toBean(jsonObject2,
  16. Student.class);
  17. list1.add(stu2);
  18. }
  19. System.out.println(list1);
  20. }
  21. }
  22. /*
  23. 打印结果:
  24. [{"password":"111111","username":"lwc"},{"password":"222222","username":"nxj"}]
  25. [用户: lwc 密码:111111, 用户: nxj 密码:222222]
  26. */
详情见:

扩展: 关于hibernate懒加载关联查询问题

问题:

net.sf.json.JSONException: There is a cycle in the hierarchy!
在一对多关系中因为懒加载的问题会导致,
情况一:
 对于页面不需要的关联对象直接使用
sonconfig.setExcludes排除就可以了
情况二:
 对于页面需要的关联对象:
 1.先在many to one 上加上lazy="false" ,使得对象立刻加载否则json转换无法进行
 2.然后在使用sonconfig.setExcludes排除循环的项目。

例:
  JsonConfig jsonconfig = new JsonConfig();
        jsonconfig.setExcludes(new String[]{"cust_link_id","customerLevel","customerInfoSource","customerIndustry"});
String string = JSONArray.fromObject(pageBean.getList(),jsonconfig).toString();

这里我们使用另外的工具类进行加载:fastjson
String jsonString = com.alibaba.fastjson.JSON.toJSONString(pageBean.getList());
        System.out.println(jsonString);

注意:还是会产生递归效果所以需要在查询类的对应的那个属性上@JSONField(serialize=false) 停止递归查询

经验分享 程序员 微信小程序 职场和发展