json除了可以用于前台传递,还可用于后台之间传递。它可以传递List,Map,Bean等类型的数据。
例如: User u1=new User();
u1.setUsername("zy");
u1.setPassword("123");
User u2=new User();
u2.setUsername("msl");
u2.setPassword("456");
List list = new ArrayList(); //把两个对象放进list中
list.add(u1);
list.add(u2);
JSONArray jsonArray = JSONArray.fromObject( list ); //把list放进json数组
Map map = new HashMap();
map.put("message", "111");
map.put("users", jsonArray); //把json数组做为一个值放进Map中
JSONObject jsonObject = JSONObject.fromObject(map); //把map放进json对象中
PrintWriter out = response.getWriter();
out.print(jsonObject); // 传递json
传递的json格式为: {"message":"111","users":[{"password":"123","username":"zy"},{"password":"456","username":"msl"}]}
在接收端的java文件中取:
returnJson是从输入流中得到的json格式的字符串。输出为:
{"message":"111","users":[{"password":"123","username":"zy"}, {"password":"456","username":"msl"}]}
if(returnJson != null && returnJson != ""){
String strJson = returnJson.replace("?(", "").replace(")", "").replace(";", "");
if(strJson.startsWith("{")){
JSONObject jsonObject = JSONObject.fromObject(strJson);
JSONArray jsonArray = JSONArray.fromObject(jsonObject.get("users"));
for (int i = 0, len = jsonArray.size(); i < len; i++) {
JSONObject jsonUser = jsonArray.getJSONObject(i);
User vo = (User)JSONObject.toBean(jsonUser, User.class);
System.out.println(vo.getUsername()+":"+vo.getPassword());
}
}
}