net.sf.json.JSON的一般使用说明
1.对pojo和字符创进行解析
注意:net.sf.json.JSON是根据pojo里面的get方法来转json对象的,如果你需要几个连载一起的属性,只需要写
public String getName({
return region+subarea+province ;
})
就多一个name属性的值,而无需重新定义属性
- public class Test {
- public static void main(String[] args) {
- // JavaBean对象转json字符串
- Student stu1 = new Student("lwc", "111111");
- JSONObject jsonObject = JSONObject.fromObject(stu1);
- System.out.println(jsonObject);
- // json字符串转JavaBean
- String jsondata = "{"password":"111111","username":"lwc"}";
- JSONObject jsonObject1 = JSONObject.fromObject(jsondata);
- Student stu2 = (Student) JSONObject.toBean(jsonObject1, Student.class);
- System.out.println(stu2);
- }
- }
- /*
- 打印结果:
- {"password":"111111","username":"lwc"}
- 用户: lwc 密码:111111
- */
不需要json解析的数据:
JsonConfig jsonConfig = new JsonConfig;
jsonConfig.setexcludes(new String[]{"currentPage","totalPage","detchedcriteria"})2.对list进行解析
- public class Test {
- public static void main(String[] args) {
- // List转json字符串
- List list = new ArrayList();
- list.add(new Student("lwc", "111111"));
- list.add(new Student("nxj", "222222"));
- JSONArray jsonArray = JSONArray.fromObject(list);
- System.out.println(jsonArray);
- // json字符串转List
- List list1 = new ArrayList();
- String jsondata = "[{"password":"111111","username":"lwc"},{"password":"222222","username":"nxj"}]";
- JSONArray jsonArray1 = JSONArray.fromObject(jsondata);
- for (int i = 0; i < jsonArray1.size(); i++) {
- JSONObject jsonObject2 = jsonArray1.getJSONObject(i);
- Student stu2 = (Student) JSONObject.toBean(jsonObject2,
- Student.class);
- list1.add(stu2);
- }
- System.out.println(list1);
- }
- }
- /*
- 打印结果:
- [{"password":"111111","username":"lwc"},{"password":"222222","username":"nxj"}]
- [用户: lwc 密码:111111, 用户: nxj 密码:222222]
- */
扩展: 关于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) 停止递归查询
