- 浏览: 167829 次
- 性别:
- 来自: 北京
文章分类
- 全部博客 (81)
- UI (6)
- 后台 (22)
- 数据库 (3)
- 其他 (3)
- 问题集 (5)
- android (0)
- 随笔 (2)
- lucene (0)
- htmlParser (1)
- python (14)
- mongodb (1)
- HTTP (1)
- eclipse (1)
- EXTJS (2)
- Spring (1)
- maven (4)
- WEB JS (2)
- java tree (1)
- javascript ActionScript (1)
- 工具 (2)
- httpclient (1)
- tomcat gzip (1)
- 线程 (1)
- 数据库 MYSQL (1)
- 后台 缓存 (1)
- linux (3)
- SQL (1)
- hadoop (1)
最新评论
-
asqin:
getFileIO 时 in 对象为null
java修改,读取properties文件 -
holleyangyanges:
你试过你的代码吗?
HttpClient CAS -
a455642158:
tks……
java修改,读取properties文件 -
faikr:
请问,这个子表的数据,你是怎么和主表相关字段做对应的?比如,我 ...
jquery之jquerygrid-subgrid -
jrius:
这种方式 应该是抓不到的,百度指数使用了amf格式
JAVA抓取百度指数数据
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包:
当然你也可以用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、 新建JsonlibTest测试类,基本代码如下:
package com.hoo.test;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONFunction;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.PropertyFilter;
import net.sf.json.xml.XMLSerializer;
import org.apache.commons.beanutils.PropertyUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.hoo.entity.Birthday;
import com.hoo.entity.Student;
/**
* <b>function:</b> 用json-lib转换java对象到JSON字符串
* 读取json字符串到java对象,序列化jsonObject到xml
* json-lib-version: json-lib-2.3-jdk15.jar
* 依赖包:
* commons-beanutils.jar
* commons-collections-3.2.jar
* ezmorph-1.0.3.jar
* commons-lang.jar
* commons-logging.jar
* @author hoojo
* @createDate Nov 28, 2010 2:28:39 PM
* @file JsonlibTest.java
* @package com.hoo.test
* @project WebHttpUtils
* @blog http://blog.csdn.net/IBM_hoojo
* @email hoojo_@126.com
* @version 1.0
*/
@SuppressWarnings({ "deprecation", "unchecked" })
public class JsonlibTest {
private JSONArray jsonArray = null;
private JSONObject jsonObject = null;
private Student bean = null;
@Before
public void init() {
jsonArray = new JSONArray();
jsonObject = new JSONObject();
bean = new Student();
bean.setAddress("address");
bean.setEmail("email");
bean.setId(1);
bean.setName("haha");
Birthday day = new Birthday();
day.setBirthday("2010-11-22");
bean.setBirthday(day);
}
@After
public void destory() {
jsonArray = null;
jsonObject = null;
bean = null;
System.gc();
}
public final void fail(String string) {
System.out.println(string);
}
public final void failRed(String string) {
System.err.println(string);
}
}
上面的init会在每个方法之前运行,destory会在每个方法完成后执行。分别用到了junit的@Before、@After注解,如果你对junit的这些注解不是很了解,可以看看junit官方的测试用例的example和doc;
JSONObject是将Java对象转换成一个json的Object形式,JSONArray是将一个Java对象转换成json的Array格式。
那什么是json的Object形式、Array形式?
用通俗易懂的方法将,所谓的json的Object形式就是一个花括号里面存放的如JavaMap的键值对,如:{name:’hoojo’, age: 24};
那么json的Array形式呢?
就是中括号,括起来的数组。如:[ ‘json’, true, 22];
如果你还想了解更多json方面的知识,请看:http://www.json.org/json-zh.html
除了上面的JSONArray、JSONObject可以将Java对象转换成JSON或是相反,将JSON字符串转换成Java对象,还有一个对象也可以完成上面的功能,它就是JSONSerializer;下面我们就来看看它们是怎么玩转Java对象和JSON的。
二、 Java对象序列化成JSON对象
1、 将JavaObject转换吃JSON字符串
在JsonlibTest中添加如下代码:
/*=========================Java Object >>>> JSON String ===========================*/
/**
* <b>function:</b>转Java Bean对象到JSON
* @author hoojo
* @createDate Nov 28, 2010 2:35:54 PM
*/
@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这个对象,这个对象可以在序列化的时候对JavaObject的数据进行处理、过滤等
上面的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##################
address@address#null#0#null#null#null
birthday@2010-11-22##修改过的日期#null#0#address#null#null
email@email#null#0#address#null#null
id@1#null#0#address#null#null
name@haha#null#0#address#null#null
Student:haha#0#address#null#null
2、 将JavaList集合转换吃JSON字符串
/**
* <b>function:</b>转换Java List集合到JSON
* @author hoojo
* @createDate Nov 28, 2010 2:36:15 PM
*/
@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对象
/**
* <b>function:</b>转Java Map对象到JSON
* @author hoojo
* @createDate Nov 28, 2010 2:37:35 PM
*/
@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
/**
* <b>function:</b> 转换更多数组类型到JSON
* @author hoojo
* @createDate Nov 28, 2010 2:39:19 PM
*/
@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对象
private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"}," +
"\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
/**
* <b>function:</b>将json字符串转化为java对象
* @author hoojo
* @createDate Nov 28, 2010 3:01:16 PM
*/
@Test
public void readJSON2Bean() {
fail("==============JSON Object String >>> Java Bean ==================");
jsonObject = JSONObject.fromObject(json);
Student stu = (Student) JSONObject.toBean(jsonObject, Student.class);
fail(stu.toString());
}
运行后,结果如下:
==============JSON Object String >>> Java Bean ==================
tom#22#chian#2010-11-22#email@123.com
2、 将json字符串转换成动态Java对象(MorphDynaBean)
private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
"\"email\":\"email@123.com\",\"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());
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@123.com
tom
3、 将json字符串转成Java的Array数组
private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
"\"email\":\"email@123.com\",\"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);
fail(JSONArray.fromObject(json).join(""));
fail(os[0].toString());
Student[] stus = (Student[]) JSONArray.toArray(jsonArray, Student.class);
System.out.println(stus.length);
System.out.println(stus[0]);
} catch (Exception e) {
e.printStackTrace();
}
}
运行的结果如下:
==============JSON Arry String >>> Java Array ==================
#%%%{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}
1
{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}
{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}
1
tom#22#chian#2010-11-22#email@123.com
4、 将JSON字符串转成Java的List集合
private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
"\"email\":\"email@123.com\",\"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());
System.out.println(list.get(0));
list = JSONArray.toList(jsonArray);
System.out.println(list.size());
System.out.println(list.get(0));//MorphDynaBean
} catch (Exception e) {
e.printStackTrace();
}
}
运行后结果如下:
==============JSON Arry String >>> Java List ==================
1
tom#22#chian#2010-11-22#email@123.com
1
net.sf.ezmorph.bean.MorphDynaBean@141b571[
{id=22, birthday=net.sf.ezmorph.bean.MorphDynaBean@b23210[
{birthday=2010-11-22}
], address=chian, email=email@123.com, name=tom}
]
5、 将json字符串转换成Collection接口
private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
"\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
@Test
public void readJSON2Collection() {
try {
fail("==============JSON Arry String >>> Java Collection ==================");
json = "[" + json + "]";
jsonArray = JSONArray.fromObject(json);
Collection<Student> con = JSONArray.toCollection(jsonArray, Student.class);
System.out.println(con.size());
Object[] stt = con.toArray();
System.out.println(stt.length);
fail(stt[0].toString());
} catch (Exception e) {
e.printStackTrace();
}
}
刚才上面的将json转换成list提示该方法过时,这里有toCollection,可以用此方法代替toList方法;运行后结果如下:
==============JSON Arry String >>> Java Collection ==================
1
1
tom#22#chian#2010-11-22#email@123.com
6、 将json字符串转换成Map集合
@Test
public void readJSON2Map() {
try {
fail("==============JSON Arry 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);
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对XML的支持
1、 将Java对象到XML
/*============================Java Object >>>>> XML ==========================*/
/**
* <b>function:</b> 转换Java对象到XML
* 需要额外的jar包:xom.jar
* @author hoojo
* @createDate Nov 28, 2010 2:39:55 PM
*/
@Test
public void writeObject2XML() {
XMLSerializer xmlSerializer = new XMLSerializer();
fail("==============Java String Array >>> XML ==================");
//xmlSerializer.setElementName("bean");
fail(xmlSerializer.write(JSONArray.fromObject(bean)));
String[] sa = {"a", "b", "c"};
fail("==============Java String Array >>> XML ==================");
fail(xmlSerializer.write(JSONArray.fromObject(sa)));
fail("==============Java boolean Array >>> XML ==================");
boolean[] bo = { true, false, true };
fail(xmlSerializer.write(JSONArray.fromObject(bo)));
fail(xmlSerializer.write(JSONSerializer.toJSON(bo)));
Object[] o = { 1, "a", true, 'A', sa, bo };
fail("==============Java Object Array >>> JSON Array ==================");
fail(xmlSerializer.write(JSONArray.fromObject(o)));
fail(xmlSerializer.write(JSONSerializer.toJSON(o)));
fail("==============Java String >>> JSON ==================");
fail(xmlSerializer.write(JSONArray.fromObject("['json','is','easy']")).toString());
fail(xmlSerializer.write(JSONObject.fromObject("{'json':'is easy'}")).toString());
fail(xmlSerializer.write(JSONSerializer.toJSON("['json','is','easy']")).toString());
}
主要运用的是XMLSerializer的write方法,这个方法可以完成java对象到xml的转换,不过你很容易就可以看到这个xml序列化对象,需要先将java对象转成json对象,然后再将json转换吃xml文档。
运行后结果如下:
==============Java String Array >>> XML ==================
<?xml version="1.0" encoding="UTF-8"?>
<a><e class="object">
<address type="string">address</address><birthday class="object"><birthday type="string">2010-11-22</birthday></birthday>
<email type="string">email</email><id type="number">1</id><name type="string">haha</name>
</e></a>
==============Java String Array >>> XML ==================
<?xml version="1.0" encoding="UTF-8"?>
<a><e type="string">a</e><e type="string">b</e><e type="string">c</e></a>
==============Java boolean Array >>> XML ==================
<?xml version="1.0" encoding="UTF-8"?>
<a><e type="boolean">true</e><e type="boolean">false</e><e type="boolean">true</e></a>
<?xml version="1.0" encoding="UTF-8"?>
<a><e type="boolean">true</e><e type="boolean">false</e><e type="boolean">true</e></a>
==============Java Object Array >>> JSON Array ==================
<?xml version="1.0" encoding="UTF-8"?>
<a><e type="number">1</e><e type="string">a</e><e type="boolean">true</e><e type="string">A</e><e class="array">
<e type="string">a</e><e type="string">b</e><e type="string">c</e></e><e class="array"><e type="boolean">true</e>
<e type="boolean">false</e><e type="boolean">true</e></e></a>
<?xml version="1.0" encoding="UTF-8"?>
<a><e type="number">1</e><e type="string">a</e><e type="boolean">true</e><e type="string">A</e><e class="array">
<e type="string">a</e><e type="string">b</e><e type="string">c</e></e><e class="array"><e type="boolean">true</e>
<e type="boolean">false</e><e type="boolean">true</e></e></a>
==============Java String >>> JSON ==================
<?xml version="1.0" encoding="UTF-8"?>
<a><e type="string">json</e><e type="string">is</e><e type="string">easy</e></a>
<?xml version="1.0" encoding="UTF-8"?>
<o><json type="string">is easy</json></o>
<?xml version="1.0" encoding="UTF-8"?>
<a><e type="string">json</e><e type="string">is</e><e type="string">easy</e></a>
上面的节点名称有点乱,你可以通过setElementName设置节点名称
2、 将XML转换成Java对象
/*============================XML String >>>>> Java Object ==========================*/
/**
* <b>function:</b>转换xml文档到java对象
* @author hoojo
* @createDate Nov 28, 2010 3:00:27 PM
*/
@Test
public void readXML2Object() {
XMLSerializer xmlSerializer = new XMLSerializer();
fail("============== XML >>>> Java String Array ==================");
String[] sa = {"a", "b", "c"};
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONArray.fromObject(sa)));
fail(jsonArray.toString());
String[] s = (String[]) JSONArray.toArray(jsonArray, String.class);
fail(s[0].toString());
fail("============== XML >>>> Java boolean Array ==================");
boolean[] bo = { true, false, true };
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONArray.fromObject(bo)));
bo = (boolean[]) JSONArray.toArray(jsonArray, boolean.class);
fail(bo.toString());
System.out.println(bo[0]);
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONSerializer.toJSON(bo)));
bo = (boolean[]) JSONArray.toArray(jsonArray, boolean.class);
fail(bo.toString());
System.out.println(bo[0]);
fail("==============Java Object Array >>> JSON Array ==================");
Object[] o = { 1, "a", true, 'A', sa, bo };
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONArray.fromObject(o)));
System.out.println(jsonArray.getInt(0));
System.out.println(jsonArray.get(1));
System.out.println(jsonArray.getBoolean(2));
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONSerializer.toJSON(o)));
System.out.println(jsonArray.get(4));
System.out.println(jsonArray.getJSONArray(5).get(0));
System.out.println(jsonArray.get(5));
fail("==============Java String >>> JSON ==================");
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONArray.fromObject("['json','is','easy']")).toString());
s = (String[]) JSONArray.toArray(jsonArray, String.class);
fail(s[0].toString());
jsonObject = (JSONObject) xmlSerializer.read(xmlSerializer.write(JSONObject.fromObject("{'json':'is easy'}")).toString());
Object obj = JSONObject.toBean(jsonObject);
System.out.println(obj);
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONSerializer.toJSON("['json','is','easy']")).toString());
s = (String[]) JSONArray.toArray(jsonArray, String.class);
fail(s[1].toString());
}
主要运用到XMLSerializer的read方法,将xml内容读取后,转换成Java对象。运行后结果如下:
============== XML >>>> Java String Array ==================
["a","b","c"]
a
============== XML >>>> Java boolean Array ==================
[Z@15856a5
true
[Z@79ed7f
true
==============Java Object Array >>> JSON Array ==================
1
a
true
["a","b","c"]
true
["true","false","true"]
==============Java String >>> JSON ==================
json
net.sf.ezmorph.bean.MorphDynaBean@c09554[
{json=is easy}
]
is
3、 将xml的字符串内容,转换成Java的Array对象
@Test
public void testReadXml2Array() {
String str = "<a class=\"array\">" +
"<e type=\"function\" params=\"i,j\">" +
"return matrix[i][j];" +
"</e>" +
"</a>";
JSONArray json = (JSONArray) new XMLSerializer().read(str);
fail(json.toString());
}
上面是一段xml字符串格式的文档,将其转换为JSONArray对象。转换后结果如下:
[function(i,j){ return matrix[i][j]; }]
就是一个数组;
一、 准备工作
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包:
当然你也可以用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、 新建JsonlibTest测试类,基本代码如下:
package com.hoo.test;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONFunction;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.PropertyFilter;
import net.sf.json.xml.XMLSerializer;
import org.apache.commons.beanutils.PropertyUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.hoo.entity.Birthday;
import com.hoo.entity.Student;
/**
* <b>function:</b> 用json-lib转换java对象到JSON字符串
* 读取json字符串到java对象,序列化jsonObject到xml
* json-lib-version: json-lib-2.3-jdk15.jar
* 依赖包:
* commons-beanutils.jar
* commons-collections-3.2.jar
* ezmorph-1.0.3.jar
* commons-lang.jar
* commons-logging.jar
* @author hoojo
* @createDate Nov 28, 2010 2:28:39 PM
* @file JsonlibTest.java
* @package com.hoo.test
* @project WebHttpUtils
* @blog http://blog.csdn.net/IBM_hoojo
* @email hoojo_@126.com
* @version 1.0
*/
@SuppressWarnings({ "deprecation", "unchecked" })
public class JsonlibTest {
private JSONArray jsonArray = null;
private JSONObject jsonObject = null;
private Student bean = null;
@Before
public void init() {
jsonArray = new JSONArray();
jsonObject = new JSONObject();
bean = new Student();
bean.setAddress("address");
bean.setEmail("email");
bean.setId(1);
bean.setName("haha");
Birthday day = new Birthday();
day.setBirthday("2010-11-22");
bean.setBirthday(day);
}
@After
public void destory() {
jsonArray = null;
jsonObject = null;
bean = null;
System.gc();
}
public final void fail(String string) {
System.out.println(string);
}
public final void failRed(String string) {
System.err.println(string);
}
}
上面的init会在每个方法之前运行,destory会在每个方法完成后执行。分别用到了junit的@Before、@After注解,如果你对junit的这些注解不是很了解,可以看看junit官方的测试用例的example和doc;
JSONObject是将Java对象转换成一个json的Object形式,JSONArray是将一个Java对象转换成json的Array格式。
那什么是json的Object形式、Array形式?
用通俗易懂的方法将,所谓的json的Object形式就是一个花括号里面存放的如JavaMap的键值对,如:{name:’hoojo’, age: 24};
那么json的Array形式呢?
就是中括号,括起来的数组。如:[ ‘json’, true, 22];
如果你还想了解更多json方面的知识,请看:http://www.json.org/json-zh.html
除了上面的JSONArray、JSONObject可以将Java对象转换成JSON或是相反,将JSON字符串转换成Java对象,还有一个对象也可以完成上面的功能,它就是JSONSerializer;下面我们就来看看它们是怎么玩转Java对象和JSON的。
二、 Java对象序列化成JSON对象
1、 将JavaObject转换吃JSON字符串
在JsonlibTest中添加如下代码:
/*=========================Java Object >>>> JSON String ===========================*/
/**
* <b>function:</b>转Java Bean对象到JSON
* @author hoojo
* @createDate Nov 28, 2010 2:35:54 PM
*/
@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这个对象,这个对象可以在序列化的时候对JavaObject的数据进行处理、过滤等
上面的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##################
address@address#null#0#null#null#null
birthday@2010-11-22##修改过的日期#null#0#address#null#null
email@email#null#0#address#null#null
id@1#null#0#address#null#null
name@haha#null#0#address#null#null
Student:haha#0#address#null#null
2、 将JavaList集合转换吃JSON字符串
/**
* <b>function:</b>转换Java List集合到JSON
* @author hoojo
* @createDate Nov 28, 2010 2:36:15 PM
*/
@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对象
/**
* <b>function:</b>转Java Map对象到JSON
* @author hoojo
* @createDate Nov 28, 2010 2:37:35 PM
*/
@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
/**
* <b>function:</b> 转换更多数组类型到JSON
* @author hoojo
* @createDate Nov 28, 2010 2:39:19 PM
*/
@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对象
private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"}," +
"\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
/**
* <b>function:</b>将json字符串转化为java对象
* @author hoojo
* @createDate Nov 28, 2010 3:01:16 PM
*/
@Test
public void readJSON2Bean() {
fail("==============JSON Object String >>> Java Bean ==================");
jsonObject = JSONObject.fromObject(json);
Student stu = (Student) JSONObject.toBean(jsonObject, Student.class);
fail(stu.toString());
}
运行后,结果如下:
==============JSON Object String >>> Java Bean ==================
tom#22#chian#2010-11-22#email@123.com
2、 将json字符串转换成动态Java对象(MorphDynaBean)
private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
"\"email\":\"email@123.com\",\"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());
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@123.com
tom
3、 将json字符串转成Java的Array数组
private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
"\"email\":\"email@123.com\",\"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);
fail(JSONArray.fromObject(json).join(""));
fail(os[0].toString());
Student[] stus = (Student[]) JSONArray.toArray(jsonArray, Student.class);
System.out.println(stus.length);
System.out.println(stus[0]);
} catch (Exception e) {
e.printStackTrace();
}
}
运行的结果如下:
==============JSON Arry String >>> Java Array ==================
#%%%{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}
1
{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}
{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}
1
tom#22#chian#2010-11-22#email@123.com
4、 将JSON字符串转成Java的List集合
private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
"\"email\":\"email@123.com\",\"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());
System.out.println(list.get(0));
list = JSONArray.toList(jsonArray);
System.out.println(list.size());
System.out.println(list.get(0));//MorphDynaBean
} catch (Exception e) {
e.printStackTrace();
}
}
运行后结果如下:
==============JSON Arry String >>> Java List ==================
1
tom#22#chian#2010-11-22#email@123.com
1
net.sf.ezmorph.bean.MorphDynaBean@141b571[
{id=22, birthday=net.sf.ezmorph.bean.MorphDynaBean@b23210[
{birthday=2010-11-22}
], address=chian, email=email@123.com, name=tom}
]
5、 将json字符串转换成Collection接口
private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
"\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
@Test
public void readJSON2Collection() {
try {
fail("==============JSON Arry String >>> Java Collection ==================");
json = "[" + json + "]";
jsonArray = JSONArray.fromObject(json);
Collection<Student> con = JSONArray.toCollection(jsonArray, Student.class);
System.out.println(con.size());
Object[] stt = con.toArray();
System.out.println(stt.length);
fail(stt[0].toString());
} catch (Exception e) {
e.printStackTrace();
}
}
刚才上面的将json转换成list提示该方法过时,这里有toCollection,可以用此方法代替toList方法;运行后结果如下:
==============JSON Arry String >>> Java Collection ==================
1
1
tom#22#chian#2010-11-22#email@123.com
6、 将json字符串转换成Map集合
@Test
public void readJSON2Map() {
try {
fail("==============JSON Arry 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);
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对XML的支持
1、 将Java对象到XML
/*============================Java Object >>>>> XML ==========================*/
/**
* <b>function:</b> 转换Java对象到XML
* 需要额外的jar包:xom.jar
* @author hoojo
* @createDate Nov 28, 2010 2:39:55 PM
*/
@Test
public void writeObject2XML() {
XMLSerializer xmlSerializer = new XMLSerializer();
fail("==============Java String Array >>> XML ==================");
//xmlSerializer.setElementName("bean");
fail(xmlSerializer.write(JSONArray.fromObject(bean)));
String[] sa = {"a", "b", "c"};
fail("==============Java String Array >>> XML ==================");
fail(xmlSerializer.write(JSONArray.fromObject(sa)));
fail("==============Java boolean Array >>> XML ==================");
boolean[] bo = { true, false, true };
fail(xmlSerializer.write(JSONArray.fromObject(bo)));
fail(xmlSerializer.write(JSONSerializer.toJSON(bo)));
Object[] o = { 1, "a", true, 'A', sa, bo };
fail("==============Java Object Array >>> JSON Array ==================");
fail(xmlSerializer.write(JSONArray.fromObject(o)));
fail(xmlSerializer.write(JSONSerializer.toJSON(o)));
fail("==============Java String >>> JSON ==================");
fail(xmlSerializer.write(JSONArray.fromObject("['json','is','easy']")).toString());
fail(xmlSerializer.write(JSONObject.fromObject("{'json':'is easy'}")).toString());
fail(xmlSerializer.write(JSONSerializer.toJSON("['json','is','easy']")).toString());
}
主要运用的是XMLSerializer的write方法,这个方法可以完成java对象到xml的转换,不过你很容易就可以看到这个xml序列化对象,需要先将java对象转成json对象,然后再将json转换吃xml文档。
运行后结果如下:
==============Java String Array >>> XML ==================
<?xml version="1.0" encoding="UTF-8"?>
<a><e class="object">
<address type="string">address</address><birthday class="object"><birthday type="string">2010-11-22</birthday></birthday>
<email type="string">email</email><id type="number">1</id><name type="string">haha</name>
</e></a>
==============Java String Array >>> XML ==================
<?xml version="1.0" encoding="UTF-8"?>
<a><e type="string">a</e><e type="string">b</e><e type="string">c</e></a>
==============Java boolean Array >>> XML ==================
<?xml version="1.0" encoding="UTF-8"?>
<a><e type="boolean">true</e><e type="boolean">false</e><e type="boolean">true</e></a>
<?xml version="1.0" encoding="UTF-8"?>
<a><e type="boolean">true</e><e type="boolean">false</e><e type="boolean">true</e></a>
==============Java Object Array >>> JSON Array ==================
<?xml version="1.0" encoding="UTF-8"?>
<a><e type="number">1</e><e type="string">a</e><e type="boolean">true</e><e type="string">A</e><e class="array">
<e type="string">a</e><e type="string">b</e><e type="string">c</e></e><e class="array"><e type="boolean">true</e>
<e type="boolean">false</e><e type="boolean">true</e></e></a>
<?xml version="1.0" encoding="UTF-8"?>
<a><e type="number">1</e><e type="string">a</e><e type="boolean">true</e><e type="string">A</e><e class="array">
<e type="string">a</e><e type="string">b</e><e type="string">c</e></e><e class="array"><e type="boolean">true</e>
<e type="boolean">false</e><e type="boolean">true</e></e></a>
==============Java String >>> JSON ==================
<?xml version="1.0" encoding="UTF-8"?>
<a><e type="string">json</e><e type="string">is</e><e type="string">easy</e></a>
<?xml version="1.0" encoding="UTF-8"?>
<o><json type="string">is easy</json></o>
<?xml version="1.0" encoding="UTF-8"?>
<a><e type="string">json</e><e type="string">is</e><e type="string">easy</e></a>
上面的节点名称有点乱,你可以通过setElementName设置节点名称
2、 将XML转换成Java对象
/*============================XML String >>>>> Java Object ==========================*/
/**
* <b>function:</b>转换xml文档到java对象
* @author hoojo
* @createDate Nov 28, 2010 3:00:27 PM
*/
@Test
public void readXML2Object() {
XMLSerializer xmlSerializer = new XMLSerializer();
fail("============== XML >>>> Java String Array ==================");
String[] sa = {"a", "b", "c"};
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONArray.fromObject(sa)));
fail(jsonArray.toString());
String[] s = (String[]) JSONArray.toArray(jsonArray, String.class);
fail(s[0].toString());
fail("============== XML >>>> Java boolean Array ==================");
boolean[] bo = { true, false, true };
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONArray.fromObject(bo)));
bo = (boolean[]) JSONArray.toArray(jsonArray, boolean.class);
fail(bo.toString());
System.out.println(bo[0]);
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONSerializer.toJSON(bo)));
bo = (boolean[]) JSONArray.toArray(jsonArray, boolean.class);
fail(bo.toString());
System.out.println(bo[0]);
fail("==============Java Object Array >>> JSON Array ==================");
Object[] o = { 1, "a", true, 'A', sa, bo };
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONArray.fromObject(o)));
System.out.println(jsonArray.getInt(0));
System.out.println(jsonArray.get(1));
System.out.println(jsonArray.getBoolean(2));
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONSerializer.toJSON(o)));
System.out.println(jsonArray.get(4));
System.out.println(jsonArray.getJSONArray(5).get(0));
System.out.println(jsonArray.get(5));
fail("==============Java String >>> JSON ==================");
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONArray.fromObject("['json','is','easy']")).toString());
s = (String[]) JSONArray.toArray(jsonArray, String.class);
fail(s[0].toString());
jsonObject = (JSONObject) xmlSerializer.read(xmlSerializer.write(JSONObject.fromObject("{'json':'is easy'}")).toString());
Object obj = JSONObject.toBean(jsonObject);
System.out.println(obj);
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONSerializer.toJSON("['json','is','easy']")).toString());
s = (String[]) JSONArray.toArray(jsonArray, String.class);
fail(s[1].toString());
}
主要运用到XMLSerializer的read方法,将xml内容读取后,转换成Java对象。运行后结果如下:
============== XML >>>> Java String Array ==================
["a","b","c"]
a
============== XML >>>> Java boolean Array ==================
[Z@15856a5
true
[Z@79ed7f
true
==============Java Object Array >>> JSON Array ==================
1
a
true
["a","b","c"]
true
["true","false","true"]
==============Java String >>> JSON ==================
json
net.sf.ezmorph.bean.MorphDynaBean@c09554[
{json=is easy}
]
is
3、 将xml的字符串内容,转换成Java的Array对象
@Test
public void testReadXml2Array() {
String str = "<a class=\"array\">" +
"<e type=\"function\" params=\"i,j\">" +
"return matrix[i][j];" +
"</e>" +
"</a>";
JSONArray json = (JSONArray) new XMLSerializer().read(str);
fail(json.toString());
}
上面是一段xml字符串格式的文档,将其转换为JSONArray对象。转换后结果如下:
[function(i,j){ return matrix[i][j]; }]
就是一个数组;
发表评论
-
iptables
2012-11-08 09:24 9291、安装iptables防火墙 Cen ... -
Hadoop 查找最大数
2012-08-15 11:11 2454package com.lch.find; import ... -
Externalizable
2012-07-11 12:27 977被Serializable接口声明的类的对象的内容都将被序列化 ... -
cxf Dynamic webservice
2012-06-06 11:18 1630/** * @Title: DynamicClient ... -
枚举单例
2012-06-02 22:23 944package myproject.javatest; ... -
Java 自定义错误类【转】
2012-03-29 11:37 850原文地址 :[url] http://www.cnblogs. ... -
eclipse: Access restriction Error
2012-02-22 15:32 924在搭建项目环境时出现了以下编译错误: Access res ... -
eclipse 不自动编译java文件的问题
2012-02-21 11:14 1698「Project」菜单 「项目」菜单可以对工作台中的项目执行动 ... -
Filter指定浏览器来缓存或不缓存服务器数据
2012-02-17 15:08 1743import java.io.*; import ... -
JAVA 单例的两种模式
2012-02-16 09:52 1443/** * 单例模式:保证一个java的类只有一个实例 ... -
httpclient4 小例子
2012-02-01 16:29 1443import java.io.BufferedReader ... -
java修改,读取properties文件
2011-11-22 16:04 11798package com.ideamov.platform.ut ... -
转 HttpClient 基础
2011-01-14 11:57 670原文地址:http://blog.csdn ... -
java 综合
2011-01-12 15:34 781JAVA 打包 CMD下进入WEB目录下 jar cvf ca ... -
JBOSS HTTPS 续
2011-01-12 15:01 1514原文地址:http://docs.jboss.org/jbos ... -
JBOSS HTTPS
2011-01-12 15:00 1334<Server> <!--APR ... -
HttpClient CAS
2011-01-11 10:09 2634package com.lch.sso; import ... -
spring security2.x 统一权限管理 数据库读取权限
2010-11-30 14:41 1426最近在研究统一权限管理,在网上深找了这一块资料,虽然JAVA开 ... -
java执行CMD命令
2010-11-12 15:22 1424package com.lch.swf; impor ... -
JAVA抓取百度指数数据
2010-11-09 09:41 6529在论坛看帖子看到一则 ...
相关推荐
在Java中,处理JSON数据通常需要依赖特定的库,而“json lib json lib”显然指的是一个用于Java的JSON处理库。 “json.jar”是这个库的实现,通常是一个包含所有必要类和方法的Java类库文件,可以被Java应用程序或...
JSONlib是一个Java库,专门设计用于处理JSON(JavaScript Object Notation)数据格式。JSON作为一种轻量级的数据交换格式,被广泛应用于Web服务和客户端应用程序之间的数据传输,因为它的语法简单,易于阅读和编写,...
4. **XML与JSON互转**: JSONLib还提供了XML和JSON之间的转换功能,使得在两种格式间切换更加便捷。 5. **自定义序列化和反序列化**: 用户可以自定义类的序列化和反序列化逻辑,以适应特定需求。 **使用JSONLib的...
`json-lib`是Java中一个常用的JSON库,它提供了将Java对象转换为JSON格式以及将JSON字符串反序列化为Java对象的功能。 `json-lib-2.4-jdk15`是`json-lib`的一个特定版本,适用于JDK1.5环境。这个库依赖于其他几个...
在描述中提到的"json lib jdk15",可能意味着这个版本的JSON Lib是专门为Java Development Kit 1.5设计的,确保在那个版本的Java环境中可以正常工作。JDK 1.5是Java的一个重要版本,引入了诸如泛型、枚举、匿名内部...
这个压缩包“jsonlib”很可能包含了Jsonlib库的所有相关组件和文件。 Jsonlib的主要功能包括: 1. **JSON对象的创建**:Jsonlib允许开发者通过简单的API创建JSON对象。例如,你可以创建一个JSON对象并添加键值对,...
本篇文章将详细介绍两个流行的Java JSON解析库:Gson和Jsonlib。 ### Gson库 Gson是Google提供的一款强大的JSON库,它可以直接将Java对象转换为JSON字符串,也可以将JSON数据反序列化为Java对象。Gson的优点在于其...
在Java中,为了处理JSON数据,我们可以利用各种库,其中之一就是JsonLib。JsonLib是一个用Java编写的开源库,它提供了一系列API来方便地解析、生成和操作JSON数据。 JsonLib支持多种数据类型与JSON的转换,包括基本...
Jsonlib是一个Java库,专门设计用于处理JSON格式数据,它提供了一套全面的API,使得在Java应用程序中生成和解析JSON变得非常简单。 Jsonlib的主要功能包括: 1. **JSON对象创建**:Jsonlib允许开发者通过Java对象...
Jsonlib是一个Java库,专门用于处理JSON(JavaScript Object Notation)数据格式。JSON是一种轻量级的数据交换格式,因其简洁明了的结构和易于解析的特性,在Web服务和客户端之间广泛使用。Jsonlib则提供了方便的API...
对于Java开发者来说,"json lib的jar包"是一个非常重要的工具,它可以帮助你在Java应用中轻松地处理JSON数据。这个jar包可能包含了诸如解析JSON字符串、创建JSON对象、遍历JSON结构以及序列化和反序列化等功能。 在...
本文将深入探讨与“jsonlib所需jar包”相关的知识点,包括jsonlib库的介绍、使用场景、如何导入项目以及避免重复文件的方法。 首先,让我们了解什么是jsonlib。Jsonlib是一个用Java编写的开源库,专门用于处理JSON...
这篇博客“JSON LIB转化时间”可能探讨了如何使用JSON Lib处理日期和时间在JSON中的转换问题。 日期和时间在JSON中通常以字符串形式表示,例如"2023-03-20T10:30:00",这是因为JSON标准本身并不支持日期类型。在...
`jsonlib24_JSON_`这个标题可能指的是JSONlib的第2.4版本,这是一个针对JSON操作的库,适合那些需要在Java项目中处理JSON数据的开发者。JSONlib提供了多种方法来解析JSON字符串到Java对象,以及将Java对象转换为JSON...
而JsonLib是一个Java库,它提供了方便的JSON对象到Java对象以及Java对象到JSON对象的转换功能。JsonLib 2.4是该库的一个版本,它允许开发者在Java项目中轻松地处理JSON数据。 JsonLib支持多种数据类型与JSON对象...
在Java开发中,jsonLib是一个广泛使用的JSON处理库,它提供了丰富的API来帮助开发者进行JSON的序列化和反序列化操作。这篇博文主要探讨jsonLib支持库在Java开发中的应用和关键功能。 首先,jsonLib作为一个开源工具...
"服务器端 json lib包"即是指用于服务器端处理JSON数据的库或框架。 在Java开发环境中,一个常见的JSON库是`json-lib`。这个库提供了多种数据结构(如Map、List、Java Beans等)与JSON对象之间的转换功能,使得...
JSON-lib是一个Java库,用于将Java对象转换为JSON(JavaScript Object Notation)格式,反之亦然。这个框架使得在Java应用程序中处理JSON数据变得简单,特别是在Web开发中,JSON经常被用作轻量级的数据交换格式。...
完整json lib 2.4的jar包,包括: commons-beanutils-1.9.3.jar commons-collections-3.2.jar commons-lang-2.3.jar commons-logging-1.2.jar ezmorph-1.0.6.jar json-lib-2.4-jdk15.jar Java开发中对象转换...
总的来说,`json-lib.jar`是一个强大的JSON处理工具,为Java开发者提供了一种简单的方式来处理JSON数据,广泛应用于各种需要数据交换的Java应用程序中。通过理解和熟练使用这个库,开发者可以提高其项目的数据处理...