最近,写网站管理员,使用异步通信技术,所使用的方法是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"); Listlist = new ArrayList (); 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 map = new HashMap (); map.put("id", "0"); map.put("admin", "wjj"); map.put("pwd", "wjj"); JSONObject jsonObject = JSONObject.fromObject(map); System.out.println(jsonObject.toString()); }}