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

JSON解析之Json-lib的更多相关文章

  1. 【JSON解析】JSON解析

    前三篇博客分别介绍了xml的三种解析方法,分别是SAX,DOM,PULL解析XML,兴趣的朋友可以去看一下这[XML解析(一)]SAX解析XML,[XML解析(二)]DOM解析XML,[XML解析(三 ...

  2. 复杂json解析(json里面嵌套json)

    调用第三方接口,返回一堆json,我只想取得里面的某一个属性,但是返回的比较复杂,无法直接拿到属性,格式类似于这样: {"video":{"id":" ...

  3. hive之Json解析(普通Json和Json数组)

    一.数据准备 现准备原始json数据(test.json)如下: {"movie":"1193","rate":"5", ...

  4. Unity3d之json解析研究

    Unity3d之json解析研究     json是好东西啊!JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式      JSON简单易用,我要好好研究一下 ...

  5. UI学习笔记---第十六天XML JSON解析

    一.解析的基本概念 从事先规定好的格式中提取数据 解析的前提:提前约定好格式.数据提供方按照格式提供数据,数据方按照格式获取数据 常见解析方式XML解析JSON解析 二.XML:可扩展标记语言 XML ...

  6. iOS开发-JSON解析

    JSON(JavaScript Object Notation)在网络传输中几乎无处不在,JSON是一种轻量级的数据交换格式,是基于JavaScript(Standard ECMA-262 3rd E ...

  7. JSON解析与序列化

    JSON之所以流行,拥有与JavaScript类似的语法并不是全部原因.更重要的一个原因是,可以把JSON数据结构解析为有用的 JavaScript对象.与XML数据结构要解析成DOM文档而且从中提取 ...

  8. JSON解析字符串

    JSON解析字符串 JSON 解析字符串时,应按严格的标准,否则无法解析: str1 = '{"str":"string","number" ...

  9. Json解析与Gson解析

    本文主要介绍json最原始的解析与google提供的gson工具类解析 ①json解析 /** * 普通的json解析 * @param s * @throws JSONException */ pr ...

  10. 高手教您编写简单的JSON解析器

    编写JSON解析器是熟悉解析技术的最简单方法之一.格式非常简单.它是递归定义的,所以与解析Brainfuck相比,你会遇到轻微的挑战 ; 你可能已经使用JSON.除了最后一点之外,解析 Scheme的 ...

随机推荐

  1. 面向对象的软件project——面向对象分析

    为了解决软件危机.一些IT前辈国产软件project这个词汇,软件project它被引入到整个软件开发过程的维护. 软件project从程序的设计角度能够分为两类.一类是面向结构的软件project. ...

  2. html不常见问题汇总

    写html已经好长一段时间了,也遇到了不少问题,跟大家分享下 form是不可以嵌套的 说明:如果嵌套会有很多问题 但是可以并列 <html> <head> </head& ...

  3. Linux 常用命令汇总

    1.shutdown -s 时间 如果是想马上关机就直接输入0或者now: 2.init 0 这个是运行级别关机: 3.halt 这个命令不是很好用: 4.power off 这个命令也是很好用的. ...

  4. 深入Java虚拟机——类型装载、连接(转)

    来自http://hi.baidu.com/holder/item/c38abf02de14c7d31ff046e0 Java虚拟机通过装载.连接和初始化一个Java类型,使该类型可以被正在运行的Ja ...

  5. C++ 之 exception

    本文讲关于C++的异常的全部东西: 绝对不让异常逃离析构函数 阻止exception逃离析构函数,主要是两个原因: 1 防止在异常处理过程中的栈展开行为时,将调用terminate函数.程序将会结束, ...

  6. LevelDB初体验

    近期工作须要找一个能使用磁盘存储数据,对写要求比較苛刻,须要每秒达100000TPS,读的时候须要能10000TPS左右,不能占用太多内存.单节点满足这个要求的常见有Redis.Memcached等, ...

  7. Codeforces Round #191 (Div. 2)---A. Flipping Game

    Flipping Game time limit per test 1 second memory limit per test 256 megabytes input standard input ...

  8. kobject_create_and_add

    本文来源于源linux 3.14.3版本号/lib/kobject.c文件 /**  * kobject_create_and_add - 动态地创建kobject结构和寄存器sysfs  *  * ...

  9. zoj 3210 A Stack or A Queue? (数据结构水题)

     A Stack or A Queue? Time Limit: 1 Second      Memory Limit: 32768 KB Do you know stack and queue? ...

  10. 杭电1162Eddy&#39;s picture

    Eddy's picture Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other) Tota ...