日期:2014-05-16  浏览次数:20408 次

JSON-lib框架,转换JSON、XML不再困难

Json-lib可以将Java对象转成json格式的字符串,也可以将Java对象转换成xml格式的文档,同样可以将json字符串转换成Java对象或是将xml字符串转换成Java对象。

?

一、 准备工作 ?

?

?

?

1、 首先要去官方下载json-lib工具包

?

下载地址:

?

http://sourceforge.net/projects/json-lib/files/json-lib/json-lib-2.4/

?

目前最新的是2.4的版本,本示例中使用的是v2.3;json-lib还需要以下依赖包:

?

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

?

官方网址:http://json-lib.sourceforge.net/

?

然后在工程中添加如下jar包:

?

clip_image002

?

当然你也可以用2.4的json-lib库

?

你可以在这里看看官方提供的示例:

?

http://json-lib.sourceforge.net/usage.html

?

由于本次介绍的示例需要junit工具,所以你还需要添加junit的jar文件,版本是4.8.2版本的,下载地址:https://github.com/KentBeck/junit/downloads

?

如果你还不了解JSON是什么?那么你应该可以看看http://www.json.org/json-zh.html

?

2、 要转换的JavaBean的代码如下:

?

package com.hoo.entity;

?

public class Student {

private int id;

private String name;

private String email;

private String address;

private Birthday birthday;

?

//setter、getter

public String toString() {

return this .name + "#" + this .id + "#" + this .address + "#" + this .birthday + "#" + this .email;

}

}

?

?

Birthday.java

?

package com.hoo.entity;

?

public class Birthday {

private String birthday;

?

public Birthday(String birthday) {

super ();

this .birthday = birthday;

}

//setter、getter

public Birthday() {}

?

@Override

public String toString() {

return this .birthday;

}

}

?

注意,上面的getter、setter方法省略了,自己构建下。

?

3、 新建Js