1.后台接收json数组转成封装实体类的List:
package no.integrasco.ingentia.news.qaedition; public class Person { private String name; private int age; public String getName() { return name;
} public void setName(String name) { this.name = name;
} public int getAge() { return age;
} public void setAge(int age) { this.age = age;
}
} package no.integrasco.ingentia.news.qaedition; import java.util.List; import net.sf.json.JSONArray;
import net.sf.json.JsonConfig; public class JsonTest { /**
* @param args
*/
public static void main(String[] args) { // 转换方法1
JSONArray array = JSONArray.fromObject("[{'name':'hehe','age':22}]");
List<Person> list = JSONArray.toList(array, Person.class);// 过时方法
System.out.println(list.get(0).getName()); // 转换方法2
List<?> list2 = JSONArray.toList(array, new Person(), new JsonConfig());//参数1为要转换的JSONArray数据,参数2为要转换的目标数据,即List盛装的数据
Person person = (Person) list2.get(0);
System.out.println(person.getAge());
} }
2.从页面接收json格式的数据,在java类里面进行解析
String jsonStr = {"name":"zfj","dd":[{"ddr":"1","encrypt":"2","ff":"1","length":"23","ffe":"editStyled","ill":"1","pkor":"2","name":"zfj","isKey":"2","alias":"ffff"}],"addRelations":[{"type":"2","ld":"zfj","ld":"2"}]}; //将此字符串放在ruquest或者其他的变量里面,传递到后台。 //如放在reques中:
request.getRequestDispatcher("/geServlet?data="+jsonStr).forward(request,response); //在servlet或java类里这样接收:
String json = request.getParameter("data");
JSONObject jsonObject = JSONObject.fromObject(data);
String name = jsonObject.getString(“name”);
......
//对于数组这样接收用 JSONArray jan = (JSONArray) jsonObject.get("dd");
if(jan!=null||jan.size()!=0){
for(int i=0;i<ja.size();i++){
JSONObject jo = JSONObject.fromObject(ja.get(i));
String ff = jo.getString("ff");
......
}
}