一、引入jar包
使用JSONObject必须引用JSON-lib.jar,同时它还依赖于其他包
- common-lang.jar
- common-beanuitls.jar
- common-collections.jar
- common-logging.jar
- ezmorph.jar
二、JSONObject对象使用
JSON-lib包是一个java对象、xml、JSON互相转换的包。
1.将Java对象转换成 json字符串
Person p1=new Person(); p1.setName("刘大江"); p1.setAge(26); String jsonStr=JSONObject.fromObject(p1).toString();
2.将Java 集合转换成 json字符串
Person p1=new Person();p1.setName("A1");p1.setAge(26); Person p2=new Person();p2.setName("A2");p2.setAge(23); List personList=new ArrayList<Person>(); personList.add(p1); personList.add(p2); Map personMap=new HashMap<String, Person>(); personMap.put("p1", p1); personMap.put("p2", p2); //[{"age":26,"name":"A1"},{"age":23,"name":"A2"}] JSONArray.fromObject(personList).toString();
JSONSerializer.toJSON(personList) //[{"p2":{"name":"A2","age":23},"p1":{"name":"A1","age":26}}] JSONArray.fromObject(personMap).toString();
JSONSerializer.toJSON(personMap)
3.将json字符串转换成动态Java对象
String jsonStr="[{"name":"A2","age":23},{"name":"A1","age":26}]"; JSONArray ja=JSONArray.fromObject(jsonStr); for(int i=0;i<ja.size();i++){ JSONObject jo= ja.getJSONObject(i); //转换成JSONObject对象 System.out.println(jo.get("name")); Person p=(Person)JSONObject.toBean(jo,Person.class); //转换成JavaBean System.out.println(p.getName()); }