1、创建一个JSONObject对象
package com.resource.controller.web;
import java.util.ArrayList;
import java.util.HashMap;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class Test {
public static void main(String[] args) {
//JsonObject和JsonArray区别就是JsonObject是对象形式,JsonArray是数组形式
//创建JsonObject第一种方法
JSONObject jsonObject = new JSONObject();
jsonObject.put("UserName", "ZHULI");
jsonObject.put("age", "30");
jsonObject.put("workIn", "ALI");
System.out.println("jsonObject1:" + jsonObject);
//创建JsonObject第二种方法
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("UserName", "ZHULI");
hashMap.put("age", "30");
hashMap.put("workIn", "ALI");
System.out.println("jsonObject2:" + JSONObject.fromObject(hashMap));
//创建一个JsonArray方法1
JSONArray jsonArray = new JSONArray();
jsonArray.add(0, "ZHULI");
jsonArray.add(1, "30");
jsonArray.add(2, "ALI");
System.out.println("jsonArray1:" + jsonArray);
//创建JsonArray方法2
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("ZHULI");
arrayList.add("30");
arrayList.add("ALI");
System.out.println("jsonArray2:" + JSONArray.fromObject(arrayList));
//如果JSONArray解析一个HashMap,则会将整个对象的放进一个数组的值中
System.out.println("jsonArray FROM HASHMAP:" + JSONArray.fromObject(hashMap));
//组装一个复杂的JSONArray
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("UserName", "ZHULI");
jsonObject2.put("age", "30");
jsonObject2.put("workIn", "ALI");
jsonObject2.element("Array", arrayList);
System.out.println("jsonObject2:" + jsonObject2);
}
}
<
结果:
jsonObject1:{"UserName":"ZHULI","age":"30","workIn":"ALI"}
jsonObject2:{"workIn":"ALI","age":"30","UserName":"ZHULI"}
jsonArray1:["ZHULI","30","ALI"]
jsonArray2:["ZHULI","30","ALI"]
jsonArray FROM HASHMAP:[{"workIn":"ALI","age":"30","UserName":"ZHULI"}]
jsonObject2:{"UserName":"ZHULI","age":"30","workIn":"ALI","Array":["ZHULI","30","ALI"]}
2、解析JSON字符串
package com.resource.controller.web;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class Test {
public static void main(String[] args) {
String jsonString = "{"UserName":"ZHULI","age":"30","workIn":"ALI","Array":["ZHULI","30","ALI"]}";
//将Json字符串转为java对象
JSONObject obj = JSONObject.fromObject(jsonString);
//获取Object中的UserName
if (obj.has("UserName")) {
System.out.println("UserName:" + obj.getString("UserName"));
}
//获取ArrayObject
if (obj.has("Array")) {
JSONArray transitListArray = obj.getJSONArray("Array");
for (int i = 0; i < transitListArray.size(); i++) {
System.out.print("Array:" + transitListArray.getString(i) + " ");
}
}
}
}
返回:
UserName:ZHULI
Array:ZHULI Array:30 Array:ALI
3、基本方法介绍
(1)List集合转换成json方法
List list = new ArrayList();
list.add( "first" );
list.add( "second" );
JSONArray jsonArray2 = JSONArray.fromObject( list );
(2)Map集合转换成json方法
Map map = new HashMap();
map.put("name", "json");
map.put("bool", Boolean.TRUE);
map.put("int", new Integer(1));
map.put("arr", new String[] { "a", "b" });
map.put("func", "function(i){ return this.arr[i]; }");
JSONObject json = JSONObject.fromObject(map);
(3)Bean转换成json代码
JSONObject jsonObject = JSONObject.fromObject(new JsonBean());
(4)数组转换成json代码
boolean[] boolArray = new boolean[] { true, false, true };
JSONArray jsonArray1 = JSONArray.fromObject(boolArray);
(5)一般数据转换成json代码
JSONArray jsonArray3 = JSONArray.fromObject("['json','is','easy']" );
(6)beans转换成json代码
List list = new ArrayList();
JsonBean2 jb1 = new JsonBean2();
jb1.setCol(1);
jb1.setRow(1);
jb1.setValue("xx");
JsonBean2 jb2 = new JsonBean2();
jb2.setCol(2);
jb2.setRow(2);
jb2.setValue("");
list.add(jb1);
list.add(jb2);
JSONArray ja = JSONArray.fromObject(list);
4、与org.json比较
json-lib和org.json的使用几乎是相同的,我总结出的区别有两点:
org.json比json-lib要轻量得多,前者没有依赖任何其他jar包,而后者要依赖ezmorph和commons的lang、logging、beanutils、collections等组件
json-lib在构造bean和解析bean时比org.json要方便的多,json-lib可直接与bean互相转换,而org.json不能直接与bean相互转换而需要map作为中转,若将bean转为json数据,首先需要先将bean转换为map再将map转为json,比较麻烦。
5、实体类和JSON对象之间相互转化(依赖包jackson-all-1.7.6.jar、jsoup-1.5.2.jar)
(1)将json转化为实体POJO:
①POJO的字段可以多于json的字段值,若少于则报错:Unrecognized field “name” (Class test.json.Student), not marked as ignorable
ObjectMapper objectMapper = new ObjectMapper();
T t = objectMapper.readValue(jsonStr, obj);
②先将json字符串转换为json对象,再将json对象转换为java对象———-推荐使用
(不存在上述异常,会警告: Tried to assign property age:java.lang.String to bean of class test.json.Person)
JSONObject obj = new JSONObject().fromObject(jsonStr);//将json字符串转换为json对象
Person person = (Person)JSONObject.toBean(obj, Person.class);//将json对象转换为Person对象
注意:当其中属性有类似List , Map ,ArrayList、自定义的类型,如List teachers, 就不可以了。 会报错:MorphDynaBean cannot be cast to con.test……
在JSONObject.toBean的时候如果转换的类中有集合,可以先定义Map
在classMap中put你要转换的类中的集合名,像:
classMap.put(“teachers”, Teacher.class);
然后在toBean()的时候把参数加上, 像:
Student student=(Student) JSONObject.toBean(str, Student.class, classMap);
JSONObject obj = new JSONObject().fromObject(jsonStr);//将json字符串转换为json对象
Map<String, Class> classMap = new HashMap<String, Class>();
classMap.put("student", Student.class);
classMap.put("teacher", Teacher.class);
Person pm=(Person) JSONObject.toBean(obj, Person.class, classMap);
(2)将实体POJO转化为JSON:
①用writeValueAsString
ObjectMapper mapper = new ObjectMapper();
String jsonStr = mapper.writeValueAsString(obj);
②先将java对象转换为json对象,在将json对象转换为json字符串
JSONObject json = JSONObject.fromObject(obj);//将java对象转换为json对象
String str = json.toString();//将json对象转换为字符串
需要依赖的包:
- jackson-core-asl-1.8.5.jar
- jackson-mapper-asl-1.8.5.jar
- json-lib-2.2.1-jdk15.jar
- ezmorph.jar json-lib-2.2.2-jdk15.jar
- commons-lang.jar commons-beanutils.jar
- commons-collections.jar
- commons-logging.jar