JSON解析之Json-lib


1.Json-lib介紹

  Json-lib是一個java類庫,它用於把beans, maps, collections, java arrays and XML 傳遞給一個Json,或者返回來把Json來傳遞beans, maps, collections, java arrays and XML ,說白了就是用於處理JSON數據的,包括生成和解析過程。這個時候你肯定會疑惑那么Javascript中JSON數據類型和Java中的數據類型是如何對應起來的額,不過不用擔心,下面就給出了他們之間的對應關系。

  

JSON   Java
string <=> java.lang.String, java.lang.Character, char
number <=> java.lang.Number, byte, short, int, long, float, double
true|false <=> java.lang.Boolean, boolean
null <=> null
function <=> net.sf.json.JSONFunction
array <=> net.sf.json.JSONArray (object, string, number, boolean, function)
object <=> net.sf.json.JSONObject

  需要支出的是:雖然Javascript中的function類型不是JSON的官方格式,可是這個也是支持的。

2.Json-lib相關依賴

  Json-lib除了依賴自身的jar包以外還依賴一些其他的jar包,最新的版本是json-lib-2.4-jdk15,初次之外還需要最小依賴的其他jar包有

    

jakarta commons-lang 2.5
jakarta commons-beanutils 1.8.0
jakarta commons-collections 3.2.1
jakarta commons-logging 1.1.1
ezmorph 1.0.6

這個只是最小依賴的jar包,完整依賴的jar包包括

  

jakarta commons-lang 2.5
jakarta commons-beanutils 1.8.0
jakarta commons-collections 3.2.1
jakarta commons-logging 1.1.1
ezmorph 1.0.6
commons-httpclient-3.1.jar
groovy-all-1.7.5.jar
junit-3.8.2.jar
log4j-1.2.14.jar
oro-2.0.8.jar
xmlunit-1.0.jar
xom-1.1.jar

其他方式,如果使用的maven來作為項目管理工具,那么只需要在pom.xml中加上

<dependency>
    <groupId>net.sf.json-lib</groupId>
    <artifactId>json-lib</artifactId>
    <version>2.4</version>
</dependency>

即可,如果是Gradle那么只需要加上

'net.sf.json-lib:json-lib:2.4'

就可以了,這樣就可以把所有相關依賴的jar包加進去了。在添加jar包的時候需要注意各個jar包的版本,如果版本不匹配就會出現問題,所以建議使用maven或者gradle來管理項目,這樣就可以避免因為版本問題不匹配而引起的問題了,既然完成了jar包的引入,那么就可以開始使用Json-lib了。

3.主要對象介紹及使用

  a:JSONSerializer

  JSONSerializer可以任何java對象轉換為JSON, 這樣就能夠方法JSONObject和JSONArray使用了。如果將一個java對象傳給Json可以使用JSONSerializer.toJSON(),將一個合法的json傳給一個Java對象可以使用JSONSerializer.toJava()

  

import java.util.Date;


public class Book {
    
    int id;
    int price;
    String name;
    String author;
    Date publishDate;
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public Date getPublishDate() {
        return publishDate;
    }
    public void setPublishDate(Date publishDate) {
        this.publishDate = publishDate;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return "name:"+this.name+",author:"+this.author+",id:"+this.id+",price:"+this.price+",publishDate:"+this.publishDate.toLocaleString();
    }

}
import java.util.Date;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;


public class JSONSerializerTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Book book = new Book();
        book.setId(1);
        book.setName("java編程要領");
        book.setPrice(12);
        book.setAuthor("tomas");
        book.setPublishDate(new Date());
        
        System.out.println("JSONSerializer.toJSON()方法");
        JSON json = JSONSerializer.toJSON(book);
        System.out.println(json);
        String jsonStr = "{author=\"tomas\",id:1,price:12,publishDate:\"\"}";
        
        System.out.println("JSONSerializer.toJava()方法");
        Object tempObj =  JSONSerializer.toJava(json);
        System.out.println(Object.class.cast(book).toString());
    }    

}

結果

  

JSONSerializer.toJSON()方法
{"author":"tomas","id":1,"name":"java編程要領","price":12,"publishDate":{"date":19,"day":3,"hours":11,"minutes":40,"month":10,"seconds":43,"time":1416368443978,"timezoneOffset":-480,"year":114}}
JSONSerializer.toJava()方法
name:java編程要領,author:tomas,id:1,price:12,publishDate:2014-11-19 11:40:43

  b.處理數組和集合

  主要通過JSONArray.fromObject(arr)這個方法獲取JSONArray,進而對其進行操作,帖代碼(用到的實體Book和上面是一樣的)

  HandleArrAndCollection.java

  

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;


public class HandleArrAndCollection {
    
    public static void main(String[] args) {
        
        int []arr = {12,334,54,677,8,3};
        JSONArray jsonArray = JSONArray.fromObject(arr);
        System.out.println(jsonArray); 
        
        List<Book> list = new ArrayList<Book>();
        for(int index = 0;index < 10;index++){
            Book book = new Book();
            book.setId(index);
            book.setAuthor("author"+index);
            book.setName("name"+index);
            book.setPrice(21+index);
            book.setPublishDate(new Date());
            
            list.add(book);
        }
        JSONArray jsonList = JSONArray.fromObject(list);
        System.out.println(jsonList); 
        
    }
}

  輸出的結果效果:

  

將數組轉為JSON對象
[12,334,54,677,8,3]
將List轉為JSON對象
[{"author":"author0","id":0,"name":"name0","price":21,"publishDate":{"date":19,"day":3,"hours":17,"minutes":31,"month":10,"seconds":47,"time":1416389507482,"timezoneOffset":-480,"year":114}},{"author":"author1","id":1,"name":"name1","price":22,"publishDate":{"date":19,"day":3,"hours":17,"minutes":31,"month":10,"seconds":47,"time":1416389507482,"timezoneOffset":-480,"year":114}},{"author":"author2","id":2,"name":"name2","price":23,"publishDate":{"date":19,"day":3,"hours":17,"minutes":31,"month":10,"seconds":47,"time":1416389507482,"timezoneOffset":-480,"year":114}},{"author":"author3","id":3,"name":"name3","price":24,"publishDate":{"date":19,"day":3,"hours":17,"minutes":31,"month":10,"seconds":47,"time":1416389507482,"timezoneOffset":-480,"year":114}},{"author":"author4","id":4,"name":"name4","price":25,"publishDate":{"date":19,"day":3,"hours":17,"minutes":31,"month":10,"seconds":47,"time":1416389507482,"timezoneOffset":-480,"year":114}},{"author":"author5","id":5,"name":"name5","price":26,"publishDate":{"date":19,"day":3,"hours":17,"minutes":31,"month":10,"seconds":47,"time":1416389507482,"timezoneOffset":-480,"year":114}},{"author":"author6","id":6,"name":"name6","price":27,"publishDate":{"date":19,"day":3,"hours":17,"minutes":31,"month":10,"seconds":47,"time":1416389507482,"timezoneOffset":-480,"year":114}},{"author":"author7","id":7,"name":"name7","price":28,"publishDate":{"date":19,"day":3,"hours":17,"minutes":31,"month":10,"seconds":47,"time":1416389507482,"timezoneOffset":-480,"year":114}},{"author":"author8","id":8,"name":"name8","price":29,"publishDate":{"date":19,"day":3,"hours":17,"minutes":31,"month":10,"seconds":47,"time":1416389507482,"timezoneOffset":-480,"year":114}},{"author":"author9","id":9,"name":"name9","price":30,"publishDate":{"date":19,"day":3,"hours":17,"minutes":31,"month":10,"seconds":47,"time":1416389507482,"timezoneOffset":-480,"year":114}}]

  c.JSON處理對象

  主要通過JSONObject.fromObject(  ),來實現,可以傳遞的參數有Map,Bean,JSON字符串,也就是一個對象Object

  HandleObjects.java

  

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import junit.framework.Assert;

import org.apache.commons.beanutils.PropertyUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


public class HandleObjects {

    /**
     * @param args
     * @throws NoSuchMethodException 
     * @throws InvocationTargetException 
     * @throws IllegalAccessException 
     */
    public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {

        System.out.println( "Map對象轉JSONJSON" ); 
        Map<String,Object> map = new HashMap<String,Object>();  
        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 jsonObject1 = JSONObject.fromObject( map );  
        System.out.println( jsonObject1 ); 
        
        System.out.println( "Bean轉JSON" ); 
        Book book = new Book();
        book.setId(1);
        book.setName("java編程語言");
        book.setPrice(12);
        book.setAuthor("tomas");
        book.setPublishDate(new Date());
        
        JSONObject jsonObj2 = JSONObject.fromObject( book );  
        System.out.println( jsonObj2 ); 
        
        System.out.println( "JSON轉為BEAN" ); 
        String json = "{name=\"json\",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}";  
        JSONObject jsonObject = JSONObject.fromObject( json );  
        Object bean = JSONObject.toBean( jsonObject );  
        System.out.println(jsonObject.get( "name" ));
        System.out.println(PropertyUtils.getProperty( bean, "name" ) );
        
        System.out.println(jsonObject.get( "bool" ));
        System.out.println(PropertyUtils.getProperty( bean, "bool" ) );
        
        System.out.println(jsonObject.get( "int" ));
        System.out.println(PropertyUtils.getProperty( bean, "int" ) );
        
        System.out.println(jsonObject.get( "double" ));
        System.out.println(PropertyUtils.getProperty( bean, "double" ) );
        
        System.out.println(jsonObject.get( "func" ));
        System.out.println(PropertyUtils.getProperty( bean, "func" ) );
    
    }

}

  輸出的結果:

  

Map對象轉JSONJSON
{"arr":["a","b"],"int":1,"name":"json","func":function(i){ return this.arr[i]; },"bool":true}
Bean轉JSON
{"author":"tomas","id":1,"name":"java編程語言","price":12,"publishDate":{"date":19,"day":3,"hours":17,"minutes":38,"month":10,"seconds":35,"time":1416389915909,"timezoneOffset":-480,"year":114}}
JSON轉為BEAN
json
json
true
true
1
1
2.2
2.2
function(a){ return a; }
function(a){ return a; }

  d:處理XML

  使用起來也比較簡單,主要是獲取XML對應的JSON對象,然后通過Json-lib提供的XMLSerializer方法來進行處理(它的很多方法是非靜態的需要首先實例化)

  HandleXML.java

  

import java.io.File;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;


public class HandleXML {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JSONObject json = new JSONObject( true );
        XMLSerializer xmlSerializer = new XMLSerializer();
        String xml = xmlSerializer.write( json ); 
        System.out.println("構建簡單XML文件");
        System.out.println(xml);
        JSONObject json2 = JSONObject.fromObject("{\"name\":\"json\",\"bool\":true,\"int\":1}");  
        String xml2 = new XMLSerializer().write( json2 ); 
        System.out.println("構建稍復雜XML文件");
        System.out.println(xml2);
        JSONArray json3 = JSONArray.fromObject("[1,2,3]");  
        String xml3 = new XMLSerializer().write( json3 ); 
        System.out.println("構建數字XML文件");
        System.out.println(xml3);
        JSONArray json4 = (JSONArray) new XMLSerializer().readFromFile(new File("src/json.xml"));  
        System.out.println("通過JSON解析XML文件");
        System.out.println( json4 );  
    }

}

  輸出結果:

  

構建簡單XML文件
<?xml version="1.0" encoding="UTF-8"?>
<o null="true"/>

構建稍復雜XML文件
<?xml version="1.0" encoding="UTF-8"?>
<o><bool type="boolean">true</bool><int type="number">1</int><name type="string">json</name></o>

構建數字XML文件
<?xml version="1.0" encoding="UTF-8"?>
<a><e type="number">1</e><e type="number">2</e><e type="number">3</e></a>

通過JSON解析XML文件
[{"id":"1","name":"Java編程","price":"23","author":"Wudy"},{"id":"1","name":"Java編程","price":"23","author":"Wudy"}]

  使用的XML文件為:json.xml

<?xml version="1.0" encoding="UTF-8"?>
    <root>
        <book>
        <id>1</id>
        <name>Java編程</name>
        <price>23</price>
        <author>Wudy</author>
    </book>
    <book>
        <id>1</id>
        <name>Java編程</name>
        <price>23</price>
        <author>Wudy</author>
    </book>
    </root>

4.總結

  通過上面的程序可以看出,使用Json-lib來處理JSON時無論是生成還是解析,用到的方法都比較簡單,主要用到的對象就是JSONObject以及JSONArray,在處理XML文件時用到了XMLSerializer,總的來說很容易上手使用,比較簡單,下篇文章介紹Gson,另外一個開源類庫用來處理JSON,由Google提供的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM