JSON、JAVA互转与将页面中改变的数据转为json格式

来源:互联网 发布:淘宝会员哪几种 编辑:程序博客网 时间:2024/06/04 17:59
首先要有这个jar包:
json-lib-2.2.3-jdk15.jar

项目代码中要导的包:
Java代码  收藏代码
  1. import net.sf.json.JSONArray;  
  2. import net.sf.json.JsonConfig;  


1.java转json
Java代码  收藏代码
  1. List<Person> list=personService.pageByHql(hql, Integer.parseInt(pageNumber), Integer.parseInt(pageSize));  
  2. JsonConfig jsonConfig = new JsonConfig();  
  3. jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);  
  4. ServletActionContext.getResponse().getWriter().write((JSONArray.fromObject(list, jsonConfig)).toString());  


2.json转java
Java代码  收藏代码
  1. private String jsonstr;//页面提交过来的json  
  2. JSONArray jsonArray = JSONArray.fromObject(jsonstr);  
  3. List<Person> list=(List<Person>)JSONArray.toCollection(jsonArray,Person.class);  


3.页面中的变动数据改为json格式,即页面中的getChanges()方法
Java代码  收藏代码
  1. var rows = $('#dg').datagrid('getChanges');  
  2. var effectRow = new Object();  
  3. effectRow = JSON.stringify(rows);  


$("#dg"):数据网格id

例:将json传到后台:
Java代码  收藏代码
  1. var rows = $('#dg').datagrid('getChanges');  
  2. var effectRow = new Object();  
  3. effectRow = JSON.stringify(rows);  
  4. $.ajax({  
  5.     type:'POST',  
  6.     url:'system/person_save.do',  
  7.     datatype:'json',  
  8.     data:{jsonstr:effectRow},  
  9.     success:function(msg){  
  10.   
  11.     }  
  12. });  


4.存在主外键关联时的取值:
Java代码  收藏代码
  1. <th data-options="field:'organization',width:'65px',align:'center',editor:'text',  
  2.     formatter:function(value,rec,index){  
  3.         var name='';  
  4.         if(value!=null){  
  5.             name= value.name;  
  6.         }  
  7.         return name;  
  8.     }">机构</th> 

0 0
原创粉丝点击