刚刚学习了下json-lib,确实很好用,分享一些自己的例子。
使用json-lib 可以把json字符串与java bean、list等相互转换,官网:
http://json-lib.sourceforge.net
userbean
public class User {
private int id;
private String name;
private String birthday;
//get set 方法.....
}
beanlist
public class ListUser {
private List users;
//get set 方法
}
测试类
public class Json {
public static void main(String[] args) {
List list = new ArrayList();
for (int i = 0; i < 2; i++) {
User user = new User();
user.setId(i);
user.setName("heartneo"+i);
user.setBirthday("06/04/2012");
list.add(user);
}
JSONArray jsonArray = JSONArray.fromObject(list); //list转换成json
String jsonStr = "{\"users\":" + jsonArray + "}";//手动添加根节点
System.out.println(jsonArray);
System.out.println(jsonStr);
list.clear();
list = (List) JSONArray.toCollection(jsonArray, User.class);//得到的json转换回list
System.out.println(((User)list.get(0)).getName());
//转换带更节点的json
Map classMap = new HashMap();
classMap.put("users", User.class); //放入User类
ListUser users = (ListUser) JSONObject.toBean(JSONObject.fromObject(jsonStr), ListUser.class, classMap);//由于ListUser嵌套User所以转换时用这种方法
System.out.println(users);
JSONObject jsonObject = JSONObject.fromObject(users.getUsers().get(0)); //获取第一个对象
User u = (User) JSONObject.toBean(jsonObject, User.class); //转换回bean
System.out.println(u.getName());
}
}
输出结果
[{"birthday":"06/04/2012","id":0,"name":"heartneo0"},{"birthday":"06/04/2012","id":1,"name":"heartneo1"}]
{"users":[{"birthday":"06/04/2012","id":0,"name":"heartneo0"},{"birthday":"06/04/2012","id":1,"name":"heartneo1"}]}
heartneo0
ListUser@211d0a4f
heartneo0
附上代码和支持包。