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