天天看點

JSON解析類庫之JSON-lib --- JSON-lib類庫學習, 生成與解析json資料, json字元串與Java對象互轉

JSON解析類庫之JSON-lib --- JSON-lib類庫學習, 生成與解析json資料, json字元串與Java對象互轉

前言

JSON-lib是java項目開發中,經常用到的json資料解析與生成的Java類庫,曆史比較悠久。不過已經N年沒有更新了,且性能效率實在是很一般,在網際網路項目中是堅決不建議使用這個類庫的。該類庫依賴的jar包就有5個。但是經常在一些老項目維護中看到JSON-lib的使用。

一、什麼是 JSON

JSON(JavaScript Object Notation)(官網網站:http://www.json.org/)是 一種輕量級的資料交換格式。 易于人閱讀和編寫。同時也易于機器解析和生成。它基于 JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999 的一個子集。 JSON 采用完全獨立于語言的文本格式,但是也使用了類似于 C 語言家族的習慣(包括C, C++, C#, Java, JavaScript, Perl, Python等)。 這些特性使 JSON 成為理想的資料交換語言。

二、JSON 的兩種結構

1、“名稱/值”對的集合(A collection of name/value pairs)。不同的語言中,它被了解為對象(object),紀錄(record),結構(struct),字典(dictionary),哈希表 (hash table),有鍵清單(keyed list),或者關聯數組 (associative array)。 在 Java 語言中,我們可以将它了解成 HashMap或者對象。

  對象是一個無序的"'名稱/值'對"集合。一個對象以"{"(左括号)開始,"}"(右括号)結束。每個“名稱”後跟一            個":"(冒号);"'名稱/值' 對"之間使用","(逗号)分隔。

示例:var json = {"name":"Jack","age":90,"Marray":true};

三、JSON-lib

Json-lib 是一個 Java 類庫(官網:http://json-lib.sourceforge.net/)可以實作如下功能:

1、轉換 JavaBean, Map, Collection, Java Array 和 XML 成為 JSON格式資料。

2、轉換 JSON 格式資料成為 JavaBean對象、Map、Collection、List、Array等。

Json-lib可以将Java對象轉成JSON格式的字元串,同樣可以将JSON字元串轉換成Java對象。

Json-lib 需要的 jar 包:

官方下載下傳位址:http://sourceforge.net/projects/json-lib/files/json-lib/json-lib-2.4/  【包含源碼下載下傳】

下載下傳位址2:http://www.java2s.com/Code/Jar/j/Downloadjsonlib24jdk15sourcesjar.htm  【json-lib源碼下載下傳】

csdn下載下傳位址:http://download.csdn.net/detail/chenchunlin526/9810451 【全部jar包,還包括一個源碼包】

commons-beanutils-1.8.3.jar 【依賴包】

commons-collections-3.2.1.jar  【依賴包】

commons-lang-2.6.jar   【依賴包】

commons-logging-1.1.1.jar   【依賴包】

ezmorph-1.0.6.jar   【依賴包】

json-lib-2.4-jdk15.jar (最核心包)

四、JSON-lib 的使用

1. 将 Java數組/集合 序列化成Json對象。使用 JSONArray 可以序列化數組類型:

Java Array ---》JSON Array

Java List ---》JSON Array

Java Set ---》JSON Array

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import net.sf.json.JSONArray;

public class JsonLib {
   public static void main(String[] args) {
       /**
        * 将字元串數組解析成JSON對象
        */
       String[] str = { "Jack", "Tom", "90", "true" }; //字元串數組
       JSONArray json = JSONArray.fromObject(str); //将數組序列化成json對象
       System.err.println(json); //可以先将JSONArray類型的json對象轉換成String類型再輸出
       // System.out.println(json.toString());
       // ["Jack","Tom","90","true"]

       /**
        * 對像數組,注意數字和布而值
        */
       Object[] obj = { "北京", "上海", 89, true, 90.87 };
       JSONArray  json = JSONArray.fromObject(obj);
       System.err.println(json);
      // ["北京","上海",89,true,90.87]

      /**
        * 使用集合類List<T>
        */
       List<String> list = new ArrayList<String>();
       list.add("Jack");
       list.add("Rose");
       JSONArray  json = JSONArray.fromObject(list);
       System.err.println(json);
       // ["Jack","Rose"]
 
        /**
        * 使用 set 集
        */
       Set<Object> set = new HashSet<Object>();
       set.add("Hello");
       set.add(true);
       set.add(99);
       JSONArray json = JSONArray.fromObject(set);
       System.err.println(json);
      // [99,true,"Hello"]

   }
}
           

運作結果如下:

["Jack","Tom","90","true"]
["北京","上海",89,true,90.87]
["Jack","Rose"]
[99,true,"Hello"]
           

2. 将 JavaBean/Map 序列化成 JSON 對象。 使用JSONObject 解析:

JavaBean ---》JSON Object

Java Map ---》JSON Object

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;
public class JsonLib {
   @SuppressWarnings("static-access")
   public static void main(String[] args) {
       /**
        * 解析Map/HashMap
        */
       Map<String, Object> map = new HashMap<String, Object>();
       map.put("name", "Tom");
       map.put("age", 33);
       JSONObject jsonObject = JSONObject.fromObject(map);
       System.out.println(jsonObject);
      //{"age":33,"name":"Tom"}

      /**
        * 解析 JavaBean
        */
       Person person = new Person("A001", "Jack"); //初始化Person對象
       JSONObject  jsonObject = JSONObject.fromObject(person);
       System.out.println(jsonObject);
      //{"id":"A001","name":"Jack"}

      /**
        * 解析嵌套的對象 Map<String, Object>
        */
       map.put("person", person);
       JSONObject  jsonObject = JSONObject.fromObject(map);
       System.out.println(jsonObject);
       // {"person":{"id":"A001","name":"Jack"},"age":33,"name":"Tom"}

   }
}
           

運作結果如下:

{"age":33,"name":"Tom"}
{"id":"A001","name":"Jack"}
{"person":{"id":"A001","name":"Jack"},"age":33,"name":"Tom"}
           

3. 使用 JsonConfig 過濾屬性:适用于 JavaBean/Map

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

public class JsonLib {
   public static void main(String[] args) {
       JsonConfig config = new JsonConfig();
       config.setExcludes(new String[] { "name" }); //指定在轉換時不包含哪些屬性,此處排除name屬性
       Person person = new Person("A001", "Jack"); // 初始化Person對象
       JSONObject jsonObject = JSONObject.fromObject(person, config); //在轉換時傳入之前的配置對象                          
       System.out.println(jsonObject);
      // {"id":"A001"}
   }
}
           

運作結果如下,在運作結果中我們可以看到 name 屬性被過濾掉了:

{"id":"A001"}
           

執行個體2(過濾Bean對象中字段為空,或字段的值為空的字段)

例:Test test = new Test();

    test.setId("1");

    test.setName("zhangsan");

    jsonObject.fromobject(test).toString;

輸出:{"id":"1","name":"zhangsan"}

假如不封裝name屬性,隻封裝id屬性

    Test test = new Test();

    test.setId("1");

    jsonObject.fromobject(test).toString;

輸出:{"id":"1","name":""}

如果隻輸出:{"id":"1"} 這樣的json字元,解決方法如下代碼

public static void main(String[] args) {
  
    Test t = new Test();  
    t.id = 10;  
           
    JsonConfig jsonConfig = new JsonConfig();  
    PropertyFilter filter = new PropertyFilter() {  
            public boolean apply(Object object, String fieldName, Object fieldValue) {  
                return null == fieldValue || "" == fieldValue;  
            }  
    };  
    jsonConfig.setJsonPropertyFilter(filter);  
    System.out.println(JSONObject.fromObject(t, jsonConfig).toString());  
}  
           

如果未給對象指派用fieldName即可,如果值預設為空,設定fieldValue即可。

4. 将 JSON對象解析成(反序列化) Java Array:

JSON Array ---》Java Array

import java.util.Arrays;
import net.sf.json.JSONArray;

public class JsonLib {
   public static void main(String[] args) {
       JSONArray jsonArray = JSONArray.fromObject("[89,90,99]"); //建立JSONArray
       Object array = JSONArray.toArray(jsonArray);//轉換成Java Object
       System.out.println(array);
       // [Ljava.lang.Object;@1e5003f6
       System.out.println(Arrays.asList((Object[]) array));
       // [89, 90, 99]

   }
}
           

運作結果如下:

[Ljava.lang.Object;@1e5003f6
[89, 90, 99]
           

5. 将 Json對象解析成 JavaBean/Map(使用JSONObject的toBean()方法):

JSON Object ---》JavaBean

JSON Object ---》Map

import java.util.Map;
import net.sf.json.JSONObject;

public class JsonLib {
   @SuppressWarnings("unchecked")
   public static void main(String[] args) {
       /**
        * 将 JSON 對象轉換(解析)為 Map
        */
       String str = "{\"name\":\"Tom\",\"age\":90}";
       JSONObject jsonObject = JSONObject.fromObject(str);
       Map<String, Object> map = (Map<String, Object>) JSONObject.toBean(jsonObject, Map.class);
       System.out.println(map);
       // {age=90, name=Tom}


       /**
        * 将 JSON對象轉換(解析)為 JavaBean
        */
       str = "{\"id\":\"A001\",\"name\":\"Jack\"}";
       jsonObject = JSONObject.fromObject(str);
       System.out.println(jsonObject);   //JSONObject類型:{age=90, name=Tom}
       Person person = (Person) JSONObject.toBean(jsonObject, Person.class);
       System.out.println(person);   //Person [id=A001, name=Jack]
   }
}
           

運作結果如下:

{age=90, name=Tom}
Person [id=A001, name=Jack]
           

在将 Json 形式的字元串轉換為 JavaBean 的時候,需要注意 JavaBean 中必須有無參構造函數,否則會報如下找不到初始化方法的錯誤:

Exception in thread "main" net.sf.json.JSONException: java.lang.NoSuchMethodException: cn.sunzn.json.Person.<init>()
   at net.sf.json.JSONObject.toBean(JSONObject.java:288)
   at net.sf.json.JSONObject.toBean(JSONObject.java:233)
   at cn.sunzn.json.JsonLib.main(JsonLib.java:23)
Caused by: java.lang.NoSuchMethodException: cn.sunzn.json.Person.<init>()
   at java.lang.Class.getConstructor0(Unknown Source)
   at java.lang.Class.getDeclaredConstructor(Unknown Source)
   at net.sf.json.util.NewBeanInstanceStrategy$DefaultNewBeanInstanceStrategy.newInstance(NewBeanInstanceStrategy.java:55)
   at net.sf.json.JSONObject.toBean(JSONObject.java:282)
   ... 2 more
           

===================================================================================================================================

一、Java對象序列化成JSON對象

JSONObject是将Java對象轉換(序列化)成一個JSON的Object形式,JSONArray是将一個Java對象轉換(序列化)成JSON的Array格式。

◆那什麼是JSON的Object形式、Array形式?--- 用通俗易懂的方法講,所謂的JSON的Object形式,就是一個花括号裡面存放的如Java Map的鍵值對,如:{name:’xiaoming’, age: 24};

◆那麼JSON的Array形式呢?--- 就是中括号括起來的數組。如:[ 'json', true, 22];如果你還想了解更多json方面的知識,請看:http://www.json.org/json-zh.html除了上面的JSONArray、JSONObject可以将Java對象轉換(序列化)成JSON(或是相反:将JSON字元串轉換(反序列化))成Java對象)還有一個對象也可以完成上面的功能,它就是JSONSerializer;下面我們就來看看它們是怎麼玩轉Java對象和JSON的。

1、Java對象序列化成JSON對象【JSONSerializer、JsonConfig】

Java Bean ---》JSON Object

Java Bean ---》JSON Array

/**
 * 轉換(序列化)Java Bean對象到JSON
 */
@Test
public void writeEntity2JSON() {

    fail("==============Java Bean >>> JSON Object==================");
    fail(JSONObject.fromObject(bean).toString());
    fail("==============Java Bean >>> JSON Array  ==================");
    fail(JSONArray.fromObject(bean).toString()); //array會在最外層套上[]
    fail("==============Java Bean >>> JSON Object ==================");
    fail(JSONSerializer.toJSON(bean).toString());
    
    fail("========================JsonConfig========================");
    JsonConfig jsonConfig = new JsonConfig();   
    jsonConfig.registerJsonValueProcessor(Birthday.class, new JsonValueProcessor() {
        public Object processArrayValue(Object value, JsonConfig jsonConfig) {
            if (value == null) {
                return new Date();
            }
            return value;
        }
 
        public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
            fail("key:" + key);
            return value + "##修改過的日期";
        }
 
    });
    jsonObject = JSONObject.fromObject(bean, jsonConfig);
    
    fail(jsonObject.toString());
    Student student = (Student) JSONObject.toBean(jsonObject, Student.class);
    fail(jsonObject.getString("birthday"));
    fail(student.toString());
    
    fail("-------------------------JsonPropertyFilter---------------------------");
    jsonConfig.setJsonPropertyFilter(new PropertyFilter() {
        public boolean apply(Object source, String name, Object value) {
            fail(source + "%%%" + name + "--" + value);
            //忽略birthday屬性
            if (value != null && Birthday.class.isAssignableFrom(value.getClass())) {
                return true;
            }
            return false;
        }
    });  
    fail(JSONObject.fromObject(bean, jsonConfig).toString());
    fail("-------------------------JavaPropertyFilter---------------------------");
    jsonConfig.setRootClass(Student.class);   
    jsonConfig.setJavaPropertyFilter(new PropertyFilter() {
        public boolean apply(Object source, String name, Object value) {
            fail(name + "@" + value + "#" + source);
            if ("id".equals(name) || "email".equals(name)) {
                value = name + "@@";
                return true;
            }
            return false;
        }
    });   
    //jsonObject = JSONObject.fromObject(bean, jsonConfig);
    //student = (Student) JSONObject.toBean(jsonObject, Student.class);
    //fail(student.toString());
    student = (Student) JSONObject.toBean(jsonObject, jsonConfig);
    fail("Student:" + student.toString());
}
           

fromObject将Java對象轉換(序列化)成JSON對象,toBean将JSON對象轉換(反序列化)成Java對象;

上面方法值得注意的是,使用了JsonConfig這個對象,這個對象可以在序列化的時候,對Java Object的資料進行處理、過濾等。上面的jsonConfig的registerJsonValueProcessor方法可以完成對對象值的處理和修改,比如處理生日為null時,給一個特定的值。同樣setJsonPropertyFilter和setJavaPropertyFilter都是完成對轉換後的值的處理。

運作上面的代碼可以在控制台看到如下結果:

==============Java Bean >>> JSON Object==================
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"haha"}
==============Java Bean >>> JSON Array==================
[{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"haha"}]
==============Java Bean >>> JSON Object ==================
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"haha"}
========================JsonConfig========================
key:birthday
{"address":"address","birthday":"2010-11-22##修改過的日期","email":"email","id":1,"name":"haha"}

2010-11-22##修改過的日期
haha#1#address#null#email
-------------------------JsonPropertyFilter------------------------
haha#1#address#2010-11-22#email%%%address--address
haha#1#address#2010-11-22#email%%%birthday--2010-11-22
haha#1#address#2010-11-22#email%%%email--email
haha#1#address#2010-11-22#email%%%id--1
haha#1#address#2010-11-22#email%%%name--haha
{"address":"address","email":"email","id":1,"name":"haha"}
-------------------------JavaPropertyFilter------------------------
[email protected]#null#0#null#null#null
[email protected]##修改過的日期#null#0#address#null#null
[email protected]#null#0#address#null#null
[email protected]#null#0#address#null#null
[email protected]#null#0#address#null#null
Student:haha#0#address#null#null
           

2、 将Java List集合轉換成JSON

Java List ---》JSON Array

/**
 * 轉換Java List集合到JSON
 */
@Test
public void writeList2JSON() {
    fail("==============Java List >>> JSON Array==================");
    List<Student> stu = new ArrayList<Student>();
    stu.add(bean);
    bean.setName("jack");
    stu.add(bean);
    fail(JSONArray.fromObject(stu).toString());
    fail(JSONSerializer.toJSON(stu).toString());
}
           

運作此方法後,可以看到控制台輸出:

==============Java List >>> JSON Array==================
[{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"}]
[{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"}]
           

如果你是轉換List集合,一定得用JSONArray或是JSONSrializer提供的序列化方法。如果你用JSONObject.fromObject方法轉換List會出現異常,通常使用JSONSrializer這個JSON序列化的方法,它會自動識别你傳遞的對象的類型,然後轉換成相應的JSON字元串。

3、 将Map集合轉換成JSON對象

Java Map ---》JSON Object

/**
 * 轉Java Map對象到JSON
 */
@Test
public void writeMap2JSON() {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("A", bean);
    
    bean.setName("jack");
    map.put("B", bean);
    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]; }"); 
    fail("==============Java Map >>> JSON Object==================");
    fail(JSONObject.fromObject(map).toString());
    fail("==============Java Map >>> JSON Array ==================");
    fail(JSONArray.fromObject(map).toString());
    fail("==============Java Map >>> JSON Object==================");
    fail(JSONSerializer.toJSON(map).toString());
}
           

上面的Map集合有JavaBean、String、Boolean、Integer、以及Array和js的function函數的字元串。

運作上面的程式,結果如下:

==============Java Map >>> JSON Object==================
{"arr":["a","b"],"A":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"int":1,
"B":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"name":"json",
"func":function(i){ return this.arr[i]; },"bool":true}
==============Java Map >>> JSON Array ==================
[{"arr":["a","b"],"A":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"int":1,
"B":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"name":"json",
"func":function(i){ return this.arr[i]; },"bool":true}]
==============Java Map >>> JSON Object==================
{"arr":["a","b"],"A":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"int":1,
"B":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"name":"json",
"func":function(i){ return this.arr[i]; },"bool":true}
           

4、 将更多類型轉換成JSON

**
 * 轉換更多數組類型到JSON
 */
@Test
public void writeObject2JSON() {
    String[] sa = {"a", "b", "c"};
    fail("==============Java StringArray >>> JSON Array ==================");
    fail(JSONArray.fromObject(sa).toString());
    fail(JSONSerializer.toJSON(sa).toString());
    fail("==============Java boolean Array >>> JSON Array ==================");
    boolean[] bo = { true, false, true };
    fail(JSONArray.fromObject(bo).toString());
    fail(JSONSerializer.toJSON(bo).toString());
    Object[] o = { 1, "a", true, 'A', sa, bo };
    fail("==============Java Object Array >>> JSON Array ==================");
    fail(JSONArray.fromObject(o).toString());
    fail(JSONSerializer.toJSON(o).toString());
    fail("==============Java String >>> JSON ==================");
    fail(JSONArray.fromObject("['json','is','easy']").toString());
    fail(JSONObject.fromObject("{'json':'is easy'}").toString());
    fail(JSONSerializer.toJSON("['json','is','easy']").toString());
    fail("==============Java JSONObject >>> JSON ==================");
    jsonObject = new JSONObject()   
        .element("string", "JSON")
        .element("integer", "1")
        .element("double", "2.0")
        .element("boolean", "true");  
    fail(JSONSerializer.toJSON(jsonObject).toString());
    
    fail("==============Java JSONArray >>> JSON ==================");
    jsonArray = new JSONArray()   
        .element( "JSON" )   
        .element( "1" )   
        .element( "2.0" )   
        .element( "true" ); 
    fail(JSONSerializer.toJSON(jsonArray).toString());
    
    fail("==============Java JSONArray JsonConfig#setArrayMode >>> JSON ==================");
    List input = new ArrayList();   
    input.add("JSON");
    input.add("1");
    input.add("2.0");
    input.add("true");   
    JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input );   
    JsonConfig jsonConfig = new JsonConfig();   
    jsonConfig.setArrayMode( JsonConfig.MODE_OBJECT_ARRAY );   
    Object[] output = (Object[]) JSONSerializer.toJava(jsonArray, jsonConfig);
    System.out.println(output[0]);
    
    fail("==============Java JSONFunction >>> JSON ==================");
    String str = "{'func': function( param ){ doSomethingWithParam(param); }}";   
    JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(str);   
    JSONFunction func = (JSONFunction) jsonObject.get("func");   
    fail(func.getParams()[0]);   
    fail(func.getText() );   
}
           

運作後結果如下:

==============Java StringArray >>> JSON Array ==================
["a","b","c"]
["a","b","c"]
==============Java boolean Array >>> JSON Array ==================
[true,false,true]
[true,false,true]
==============Java Object Array >>> JSON Array ==================
[1,"a",true,"A",["a","b","c"],[true,false,true]]
[1,"a",true,"A",["a","b","c"],[true,false,true]]
==============Java String >>> JSON ==================
["json","is","easy"]
{"json":"is easy"}
["json","is","easy"]
==============Java JSONObject >>> JSON ==================
{"string":"JSON","integer":"1","double":"2.0","boolean":"true"}
==============Java JSONArray >>> JSON ==================
["JSON","1","2.0","true"]
==============Java JSONArray JsonConfig#setArrayMode >>> JSON ==================
JSON
==============Java JSONFunction >>> JSON ==================
param
doSomethingWithParam(param);
           

這裡還有一個JSONFunction的對象,可以轉換JavaScript的function。可以擷取方法參數和方法體。

同時,還可以用JSONObject、JSONArray建構Java對象,完成Java對象到JSON字元串的轉換。

二、JSON對象反序列化成Java對象

1、 将json字元串轉成Java對象(json字元串先轉換成JSON對象,然後再轉換成Java對象)

JSON Object ---》Java Bean

private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"}," +
        "\"email\":\"[email protected]\",\"id\":22,\"name\":\"tom\"}";
/**
 * 将json字元串轉化為java對象
 */
@Test
public void readJSON2Bean() {
    fail("==============JSON Object String >>> Java Bean ==================");
    JSONObject jsonObject = JSONObject.fromObject(json);
    Student stu = (Student) JSONObject.toBean(jsonObject, Student.class);
    fail(stu.toString()); //tom#22#chian#2010-11-22#[email protected]
}
           

運作後,結果如下:

====================JSON Object String >>> Java Bean ==================
tom#22#chian#2010-11-22#[email protected]
           

執行個體2,把json對象轉換成複雜bean對象

JSON Object ---》Java Bean

public class TranslateResult {  
    private String from;    // 實際采用的源語言    
    private String to;  // 實際采用的目智語言  
    private List<ResultPair> transResult;    // 結果體    
} 
           

====

public class ResultPair {  
    private String src; // 原文  
    private String dst; // 譯文  
}  
           

核心代碼:

StringBuffer sb = new StringBuffer(); 
 
String json = "{\"from\":\"en\",\"to\":\"zh\",\"transResult\":[{\"src\":\"hello\",\"dst\":\"您好\"},{\"src\":\"beautiful\",\"dst\":\"美女\"}]}";
JSONObject jsonObject = JSONObject.fromObject(json)
Map<String, Class<ResultPair>> clazzMap = new HashMap<String, Class<ResultPair>>();  
map.put("transResult", ResultPair.class);  
TranslateResult translateResult = (TranslateResult) JSONObject.toBean(jsonObject, TranslateResult.class, clazzMap);  
List<ResultPair> list = translateResult.getTransResult();  
for (ResultPair rp : list) {  
    sb.append(rp.getDst());  
}  
System.out.println(sb); // 輸出:你好美女 
           

2、将json字元串轉換成動态Java對象(MorphDynaBean)

private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
        "\"email\":\"[email protected]\",\"id\":22,\"name\":\"tom\"}";
 
@Test
public void readJSON2DynaBean() {
    try {
        fail("==============JSON Object String >>> Java MorphDynaBean ==================");
        JSON jo = JSONSerializer.toJSON(json);
        Object o = JSONSerializer.toJava(jo);//MorphDynaBean
        fail(PropertyUtils.getProperty(o, "address").toString()); //chian
        jsonObject = JSONObject.fromObject(json);
        fail(jsonObject.getString("email"));
        o = JSONSerializer.toJava(jsonObject);//MorphDynaBean
        fail(PropertyUtils.getProperty(o, "name").toString());
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }
}
           

轉換後的對象Object是一個MorphDynaBean的動态JavaBean,通過PropertyUtils可以獲得指定的屬性的值。

運作後結果如下:

==============JSON Object String >>> Java MorphDynaBean =============
chian
[email protected]
tom
           

3、将json字元串轉成Java的Array數組

JSON Array ---》Java Array ---》Java bean

private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
        "\"email\":\"[email protected]\",\"id\":22,\"name\":\"tom\"}";
 
@Test
public void readJSON2Array() {
    try {
        fail("==============JSON Arry String >>> Java Array ==================");
        json = "[" + json + "]";
        jsonArray = JSONArray.fromObject(json);
        fail("#%%%" + jsonArray.get(0).toString());
        Object[] os = jsonArray.toArray();
        System.out.println(os.length); // 1
        
        fail(JSONArray.fromObject(json).join(""));
    //{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"[email protected]","id":22,"name":"tom"}
        fail(os[0].toString());
    //{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"[email protected]","id":22,"name":"tom"}
        Student[] stus = (Student[]) JSONArray.toArray(jsonArray, Student.class);
        System.out.println(stus.length); //1
        System.out.println(stus[0]);  //tom#22#chian#2010-11-22#[email protected]
    } catch (Exception e) {
        e.printStackTrace();
    }
}
           

運作的結果如下:

==============JSON Arry String >>> Java Array ==================
#%%%{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"[email protected]","id":22,"name":"tom"}
1
{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"[email protected]","id":22,"name":"tom"}
{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"[email protected]","id":22,"name":"tom"}
1
tom#22#chian#2010-11-22#[email protected]
           

4、将JSON字元串轉成Java的List集合(已不推薦使用)

private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
        "\"email\":\"[email protected]\",\"id\":22,\"name\":\"tom\"}";
 
@Test
public void readJSON2List() {
    try {
        fail("==============JSON Arry String >>> Java List ==================");
        json = "[" + json + "]";
        jsonArray = JSONArray.fromObject(json);
        List<Student> list = JSONArray.toList(jsonArray, Student.class);
        System.out.println(list.size()); //1
        System.out.println(list.get(0)); //tom#22#chian#2010-11-22#[email protected]
        
        list = JSONArray.toList(jsonArray);
        System.out.println(list.size()); // 1
        System.out.println(list.get(0));//MorphDynaBean 
//[email protected][{id=22,[email protected][{birthday=2010-11-22}], address=chian, [email protected], name=tom}]
    } catch (Exception e) {
        e.printStackTrace();
    }
}
           

運作後結果如下:

==============JSON Arry String >>> Java List ==================
1
tom#22#chian#2010-11-22#[email protected]
1
[email protected][
  {id=22, [email protected][
  {birthday=2010-11-22}
], address=chian, [email protected], name=tom}
]
           

5、将json字元串轉換成Collection接口

JSON Array ---》Java Collection ---》Java Bean

private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
        "\"email\":\"[email protected]\",\"id\":22,\"name\":\"tom\"}";
 
@Test
public void readJSON2Collection() {
    try {
        fail("==============JSON Array String >>> Java Collection ==================");
        json = "[" + json + "]";
        jsonArray = JSONArray.fromObject(json);
        Collection<Student> con = JSONArray.toCollection(jsonArray, Student.class);
        System.out.println(con.size()); //1
        Object[] stt = con.toArray();
        System.out.println(stt.length); // 1
        fail(stt[0].toString()); // tom#22#chian#2010-11-22#[email protected]
        
    } catch (Exception e) {
        e.printStackTrace();
    }
}
           

剛才上面的将json轉換成list提示該方法過時,這裡有toCollection,可以用此方法代替toList方法;運作後結果如下:

==============JSON Arry String >>> Java Collection ==================
1
1
tom#22#chian#2010-11-22#[email protected]
           

6、将json字元串轉換成Map集合

複雜JSON類型---》Map

@Test
public void readJSON2Map() {
    try {
        fail("==============JSON Array String >>> Java Map ==================");
        json = "{\"arr\":[\"a\",\"b\"],\"A\":{\"address\":\"address\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
        "\"email\":\"email\",\"id\":1,\"name\":\"jack\"},\"int\":1,"+
        "\"B\":{\"address\":\"address\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
        "\"email\":\"email\",\"id\":1,\"name\":\"jack\"},\"name\":\"json\",\"bool\":true}";
        jsonObject = JSONObject.fromObject(json);

        Map<String, Class<?>> clazzMap = new HashMap<String, Class<?>>();
        clazzMap.put("arr", String[].class);
        clazzMap.put("A", Student.class);
        clazzMap.put("B", Student.class);
        Map<String, ?> mapBean = (Map) JSONObject.toBean(jsonObject, Map.class, clazzMap); //關鍵代碼
        System.out.println(mapBean);
// {A=jack#1#address#2010-11-22#email, arr=[a, b], B=jack#1#address#2010-11-22#email, int=1, name=json, bool=true}
        
        Set<String> set = mapBean.keySet();
        Iterator<String> iter = set.iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            fail(key + ":" + mapBean.get(key).toString());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
           

運作後結果如下:

==============JSON Arry String >>> Java Map ==================
{A=jack#1#address#2010-11-22#email, arr=[a, b], B=jack#1#address#2010-11-22#email, int=1, name=json, bool=true}
A:jack#1#address#2010-11-22#email
arr:[a, b]
B:jack#1#address#2010-11-22#email
int:1
name:json
bool:true
           

題外話:json-lib已經停止更新了(jdk1.5之後就沒有更新過了),而且他的相關依賴包比較多(有5個依賴包,1個核心包),是以在新的項目開發中是不建議使用的,尤其是新的網際網路項目中最好别用這個庫,主要是他的性能比較差、速度慢。但是在一些需求比較簡單的項目中還是可以用的,筆者的公司的很多老項目也在用。其實他的api方法還是比較好用的,也比較直覺,易于了解。

目前,其他一些主流JSON庫的性能已遠遠超過他。主流的優秀json解析庫有:

1、Jackson(SpringMVC架構官方預設的json解析包,功能強大,性能優秀,不過api不怎麼直覺)

2、Gson(google公司開的,性能優秀,穩定性好)

3、Fastjson(阿裡巴巴開發的,号稱目前解析速度的最快的json庫,api使用簡單,易上手,性能好)等。

上面這三個庫才是目前Java領域json解析庫中,最牛B的三個庫。排在第一梯隊,性能不相上下。接下來的博文系列會分别講解這三個庫的使用方法。