最近,在写一个网站的后台管理,用到异步通讯技术,用的方法是JSON数据传送方式
需要下面几个jar文件
然后,自己写了一点点常用代码
Java的List和数组要用JSONArray对象
Map和实体用JSONObject
package com.demo; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import com.trade.entity.Users; public class TestJSON { public static void main(String[] args) { Users users = new Users(); users.setId(0); users.setUname("admin"); users.setPwd("admin"); Users users1 = new Users(); users1.setId(1); users1.setUname("admin1"); users1.setPwd("admin1"); List<Users> list = new ArrayList<Users>(); list.add(users); list.add(users1); // shitiduixiang {"id":1,"pwd":"admin1","uname":"admin1"} // JSONObject jsonObject = JSONObject.fromObject(users); // System.out.println(jsonObject.toString()); // [{"id":1,"pwd":"admin1","uname":"admin1"},{"id":0,"pwd":"","uname":""}] // list // JSONArray array = JSONArray.fromObject(list); // System.out.println(array.toString()); // {"total":2,"rows":[{"id":0,"pwd":"admin","uname":"admin"},{"id":1,"pwd":"admin1","uname":"admin1"}]} // 自己定义 // JSONObject jsonObject = new JSONObject(); // jsonObject.put("total", 2); // jsonObject.put("rows", list); // System.out.println(jsonObject.toString()); // {"id":"0","pwd":"wjj","admin":"wjj"} Map<String, String> map = new HashMap<String, String>(); map.put("id", "0"); map.put("admin", "wjj"); map.put("pwd", "wjj"); JSONObject jsonObject = JSONObject.fromObject(map); System.out.println(jsonObject.toString()); } }