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提供的。

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。