TestUser:
private String userName;
private String password;
private String old;
private String sex;
private String phone;
//1.普通的javabean转化为json格式
TestUser testUser = new TestUser();
testUser.setUserName("wangbingbing");
testUser.setPassword("123456");
testUser.setOld("18");
testUser.setPhone("15748574147");
testUser.setSex("女");
//转为JSONArray类型
JSONArray json = JSONArray.fromObject(testUser);
System.out.println(json);//[{"old":"18","password":"123456","phone":"15748574147","sex":"女","userName":"wangbingbing"}]
//转为JSONObject
JSONObject jsonObj = JSONObject.fromObject(testUser);
System.out.println(jsonObj);//{"old":"18","password":"123456","phone":"15748574147","sex":"女","userName":"wangbingbing"}
//JSONObject转化为javabean
TestUser o = (TestUser) JSONObject.toBean(jsonObj, TestUser.class);
System.out.println(o.getUserName());//wangbingbing
//2.list转为json格式
List<TestUser> users = new ArrayList<TestUser>();
TestUser testUser1 = new TestUser();
testUser1.setUserName("wangfeng");
testUser1.setPassword("789456");
testUser1.setOld("68");
testUser1.setPhone("15784571147");
testUser1.setSex("男");
users.add(testUser1);
users.add(testUser);
//list转为JSONArray
JSONArray json1 = JSONArray.fromObject(users);
System.out.println(json1.toString());//[{"old":"68","password":"789456","phone":"15784571147","sex":"男","userName":"wangfeng"},{"old":"18","password":"123456","phone":"15748574147","sex":"女","userName":"wangbingbing"}]
//list转为JSONObject
JSONObject jsonObj1 = new JSONObject();
jsonObj1.put("testUser", testUser);
jsonObj1.put("testUser1", testUser1);
System.out.println(jsonObj1);//{"testUser":{"old":"18","password":"123456","phone":"15748574147","sex":"女","userName":"wangbingbing"},"testUser1":{"old":"68","password":"789456","phone":"15784571147","sex":"男","userName":"wangfeng"}}
//map转为JSONArray
Map<String,Object> map = new HashMap<String,Object>();
map.put("testUser", testUser);
map.put("testUser1", testUser1);
JSONArray json2 = JSONArray.fromObject(map);
System.out.println(json2.toString());//[{"testUser1":{"old":"68","password":"789456","phone":"15784571147","sex":"男","userName":"wangfeng"},"testUser":{"old":"18","password":"123456","phone":"15748574147","sex":"女","userName":"wangbingbing"}}]
//map转为JSONObject
JSONObject json3 = JSONObject.fromObject(map);
System.out.println(json3);// {"testUser1":{"old":"68","password":"789456","phone":"15784571147","sex":"男","userName":"wangfeng"},"testUser":{"old":"18","password":"123456","phone":"15748574147","sex":"女","userName":"wangbingbing"}}
所需要的jar