JSON-lib framework, converting JSON and XML is no longer difficult

黄舟
Release: 2017-02-18 15:10:46
Original
1960 people have browsed it

Json-lib can convert Java objects into json format strings, and can also convert Java objects into xml format documents. It can also convert json strings into Java objects or xml strings into Java objects. .

1.Preparation

1. First of all Go to the official download json-lib toolkit

Download address:

//m.sbmmt.com/

The latest version is version 2.4. In this example v2.3 is used; json-lib also requires the following dependency packages:

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

Official website: //m.sbmmt.com/

Then add the following jar package to the project:

JSON-lib framework, converting JSON and XML is no longer difficult

Of course you can also use the 2.4 json-lib library

You can check out the official provision here Example:

//m.sbmmt.com/

Since the example introduced this time requires the junit tool, you also need to add the junit jar file, the version is 4.8.2 Version, download address: //m.sbmmt.com/

If you still don’t know what JSON is? Then you should be able to take a look at //m.sbmmt.com/

2. The code of the JavaBean to be converted is as follows:


package com.hoo.entity;
Copy after login
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
public class Student {
Copy after login
private int id;
Copy after login
private String name;
Copy after login
private String email;
Copy after login
private String address;
Copy after login
private Birthday birthday;
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
//setter、getter
Copy after login
Copy after login
public String toString() {
Copy after login
return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;
Copy after login
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login

##Birthday.java


##
package com.hoo.entity;
Copy after login
Copy after login


Copy after login
Copy after login
Copy after login
Copy after login
public class Birthday {
Copy after login
private String birthday;
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
public Birthday(String birthday) {
Copy after login
super();
Copy after login
this.birthday = birthday;
Copy after login
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
//setter、getter
Copy after login
Copy after login
public Birthday() {}
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
@Override
Copy after login
public String toString() {
Copy after login
return this.birthday;
Copy after login
}
Copy after login
}
Copy after login
Copy after login
Copy after login

Note that the above getter and setter methods are omitted, build them yourself.

3. Create a new JsonlibTest test class. The basic code is as follows:


##

package com.hoo.test;
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login

import java.lang.reflect.InvocationTargetException;
Copy after login
import java.util.ArrayList;
Copy after login
import java.util.Collection;
Copy after login
import java.util.Date;
Copy after login
import java.util.HashMap;
Copy after login
import java.util.Iterator;
Copy after login
import java.util.List;
Copy after login
import java.util.Map;
Copy after login
import java.util.Set;
Copy after login
import net.sf.json.JSON;
Copy after login
import net.sf.json.JSONArray;
Copy after login
import net.sf.json.JSONFunction;
Copy after login
import net.sf.json.JSONObject;
Copy after login
import net.sf.json.JSONSerializer;
Copy after login
import net.sf.json.JsonConfig;
Copy after login
import net.sf.json.processors.JsonValueProcessor;
Copy after login
import net.sf.json.util.PropertyFilter;
Copy after login
import net.sf.json.xml.XMLSerializer;
Copy after login
import org.apache.commons.beanutils.PropertyUtils;
Copy after login
import org.junit.After;
Copy after login
import org.junit.Before;
Copy after login
import org.junit.Test;
Copy after login
import com.hoo.entity.Birthday;
Copy after login
import com.hoo.entity.Student;
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
/**
Copy after login
Copy after login
* function: 用json-lib转换java对象到JSON字符串
Copy after login
* 读取json字符串到java对象,序列化jsonObject到xml
Copy after login
* json-lib-version: json-lib-2.3-jdk15.jar
Copy after login
* 依赖包:
Copy after login
* commons-beanutils.jar
Copy after login
* commons-collections-3.2.jar
Copy after login
* ezmorph-1.0.3.jar
Copy after login
* commons-lang.jar
Copy after login
* commons-logging.jar
Copy after login
* @author hoojo
Copy after login
Copy after login
* @createDate Nov 28, 2010 2:28:39 PM
Copy after login
* @file JsonlibTest.java
Copy after login
* @package com.hoo.test
Copy after login
* @project WebHttpUtils
Copy after login
* @blog //m.sbmmt.com/
Copy after login
* @email hoojo_@126.com
Copy after login
* @version 1.0
Copy after login
*/
Copy after login
Copy after login
@SuppressWarnings({ "deprecation", "unchecked" })
Copy after login
public class JsonlibTest {
Copy after login
private JSONArray jsonArray = null;
Copy after login
private JSONObject jsonObject = null;
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
private Student bean = null;
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
@Before
Copy after login
public void init() {
Copy after login
jsonArray = new JSONArray();
Copy after login
jsonObject = new JSONObject();
Copy after login

Copy after login
bean = new Student();
Copy after login
bean.setAddress("address");
Copy after login
bean.setEmail("email");
Copy after login
bean.setId(1);
Copy after login
bean.setName("haha");
Copy after login
Birthday day = new Birthday();
Copy after login
day.setBirthday("2010-11-22");
Copy after login
bean.setBirthday(day);
Copy after login
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
@After
Copy after login
public void destory() {
Copy after login
jsonArray = null;
Copy after login
jsonObject = null;
Copy after login
bean = null;
Copy after login
System.gc();
Copy after login
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
public final void fail(String string) {
Copy after login
System.out.println(string);
Copy after login
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
public final void failRed(String string) {
Copy after login
System.err.println(string);
Copy after login
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
}
Copy after login
Copy after login
Copy after login

上面的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方面的知识,请看://m.sbmmt.com/

除了上面的JSONArray、JSONObject可以将Java对象转换成JSON或是相反,将JSON字符串转换成Java对象,还有一个对象也可以完成上面的功能,它就是JSONSerializer;下面我们就来看看它们是怎么玩转Java对象和JSON的。

二、Java对象序列化成JSON对象

1、 将JavaObject转换吃JSON字符串

在JsonlibTest中添加如下代码:


/*=========================Java Object >>>> JSON String ===========================*/
Copy after login
/**
Copy after login
Copy after login
* function:转Java Bean对象到JSON
Copy after login
* @author hoojo
Copy after login
Copy after login
* @createDate Nov 28, 2010 2:35:54 PM
Copy after login
*/
Copy after login
Copy after login
@Test
Copy after login
public void writeEntity2JSON() {
Copy after login
fail("==============Java Bean >>> JSON Object==================");
Copy after login
fail(JSONObject.fromObject(bean).toString());
Copy after login
fail("==============Java Bean >>> JSON Array==================");
Copy after login
fail(JSONArray.fromObject(bean).toString());//array会在最外层套上[]
Copy after login
fail("==============Java Bean >>> JSON Object ==================");
Copy after login
fail(JSONSerializer.toJSON(bean).toString());
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
fail("========================JsonConfig========================");
Copy after login
JsonConfig jsonConfig = new JsonConfig();
Copy after login
Copy after login
jsonConfig.registerJsonValueProcessor(Birthday.class, new JsonValueProcessor() {
Copy after login
public Object processArrayValue(Object value, JsonConfig jsonConfig) {
Copy after login
if (value == null) {
Copy after login
return new Date();
Copy after login
}
Copy after login
Copy after login
return value;
Copy after login
}
Copy after login
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
Copy after login
fail("key:" + key);
Copy after login
return value + "##修改过的日期";
Copy after login
}
Copy after login
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
});
Copy after login
Copy after login
jsonObject = JSONObject.fromObject(bean, jsonConfig);
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
fail(jsonObject.toString());
Copy after login
Student student = (Student) JSONObject.toBean(jsonObject, Student.class);
Copy after login
fail(jsonObject.getString("birthday"));
Copy after login
fail(student.toString());
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
fail("#####################JsonPropertyFilter############################");
Copy after login
jsonConfig.setJsonPropertyFilter(new PropertyFilter() {
Copy after login
public boolean apply(Object source, String name, Object value) {
Copy after login
fail(source + "%%%" + name + "--" + value);
Copy after login
//忽略birthday属性
Copy after login
if (value != null && Birthday.class.isAssignableFrom(value.getClass())) {
Copy after login
return true;
Copy after login
}
Copy after login
Copy after login
return false;
Copy after login
}
Copy after login
Copy after login
});
Copy after login
Copy after login
fail(JSONObject.fromObject(bean, jsonConfig).toString());
Copy after login
fail("#################JavaPropertyFilter##################");
Copy after login
jsonConfig.setRootClass(Student.class);
Copy after login
jsonConfig.setJavaPropertyFilter(new PropertyFilter() {
Copy after login
public boolean apply(Object source, String name, Object value) {
Copy after login
fail(name + "@" + value + "#" + source);
Copy after login
if ("id".equals(name) || "email".equals(name)) {
Copy after login
value = name + "@@";
Copy after login
return true;
Copy after login
}
Copy after login
return false;
Copy after login
}
Copy after login
Copy after login
});
Copy after login
//jsonObject = JSONObject.fromObject(bean, jsonConfig);
Copy after login
//student = (Student) JSONObject.toBean(jsonObject, Student.class);
Copy after login
//fail(student.toString());
Copy after login
student = (Student) JSONObject.toBean(jsonObject, jsonConfig);
Copy after login
fail("Student:" + student.toString());
Copy after login
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

fromObject将Java对象转换成json字符串,toBean将json对象转换成Java对象;

上面方法值得注意的是使用了JsonConfig这个对象,这个对象可以在序列化的时候对JavaObject的数据进行处理、过滤等

上面的jsonConfig的registerJsonValueProcessor方法可以完成对象值的处理和修改,比如处理生日为null时,给一个特定的值。同样setJsonPropertyFilter和setJavaPropertyFilter都是完成对转换后的值的处理。

运行上面的代码可以在控制台看到如下结果:


==============Java Bean >>> JSON Object==================
Copy after login
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"haha"}
Copy after login
Copy after login
==============Java Bean >>> JSON Array==================
Copy after login
[{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"haha"}]
Copy after login
==============Java Bean >>> JSON Object ==================
Copy after login
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"haha"}
Copy after login
Copy after login
========================JsonConfig========================
Copy after login
key:birthday
Copy after login
{"address":"address","birthday":"2010-11-22##修改过的日期","email":"email","id":1,"name":"haha"}
Copy after login
2010-11-22##修改过的日期
Copy after login
haha#1#address#null#email
Copy after login
#####################JsonPropertyFilter############################
Copy after login
haha#1#address#2010-11-22#email%%%address--address
Copy after login
haha#1#address#2010-11-22#email%%%birthday--2010-11-22
Copy after login
haha#1#address#2010-11-22#email%%%email--email
Copy after login
haha#1#address#2010-11-22#email%%%id--1
Copy after login
haha#1#address#2010-11-22#email%%%name--haha
Copy after login
{"address":"address","email":"email","id":1,"name":"haha"}
Copy after login
#################JavaPropertyFilter##################
Copy after login
address@address#null#0#null#null#null
Copy after login
birthday@2010-11-22##修改过的日期#null#0#address#null#null
Copy after login
email@email#null#0#address#null#null
Copy after login
id@1#null#0#address#null#null
Copy after login
name@haha#null#0#address#null#null
Copy after login
Student:haha#0#address#null#null
Copy after login

2、 将JavaList集合转换吃JSON字符串


/**
Copy after login
Copy after login
Copy after login
* function:转换Java List集合到JSON
Copy after login
* @author hoojo
Copy after login
Copy after login
Copy after login
Copy after login
* @createDate Nov 28, 2010 2:36:15 PM
Copy after login
*/
Copy after login
Copy after login
Copy after login
Copy after login
@Test
Copy after login
Copy after login
Copy after login
Copy after login
public void writeList2JSON() {
Copy after login
fail("==============Java List >>> JSON Array==================");
Copy after login
List stu = new ArrayList();
Copy after login
stu.add(bean);
Copy after login
Copy after login
bean.setName("jack");
Copy after login
Copy after login
stu.add(bean);
Copy after login
Copy after login
fail(JSONArray.fromObject(stu).toString());
Copy after login
fail(JSONSerializer.toJSON(stu).toString());
Copy after login
}
Copy after login
Copy after login
Copy after login

运行此方法后,可以看到控制台输出:


==============Java List >>> JSON Array==================
Copy after login
[{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},
Copy after login
Copy after login
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"}]
Copy after login
Copy after login
[{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},
Copy after login
Copy after login
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"}]
Copy after login
Copy after login

如果你是转换List集合,一定得用JSONArray或是JSONSrializer提供的序列化方法。如果你用JSONObject.fromObject方法转换List会出现异常,通常使用JSONSrializer这个JSON序列化的方法,它会自动识别你传递的对象的类型,然后转换成相应的JSON字符串。

3、 将Map集合转换成JSON对象


/**
Copy after login
Copy after login
Copy after login
* function:转Java Map对象到JSON
Copy after login
* @author hoojo
Copy after login
Copy after login
Copy after login
Copy after login
* @createDate Nov 28, 2010 2:37:35 PM
Copy after login
*/
Copy after login
Copy after login
Copy after login
Copy after login
@Test
Copy after login
Copy after login
Copy after login
Copy after login
public void writeMap2JSON() {
Copy after login
Map map = new HashMap();
Copy after login
map.put("A", bean);
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
bean.setName("jack");
Copy after login
Copy after login
map.put("B", bean);
Copy after login
map.put("name", "json");
Copy after login
map.put("bool", Boolean.TRUE);
Copy after login
map.put("int", new Integer(1));
Copy after login
map.put("arr", new String[] { "a", "b" });
Copy after login
map.put("func", "function(i){ return this.arr[i]; }");
Copy after login
fail("==============Java Map >>> JSON Object==================");
Copy after login
Copy after login
fail(JSONObject.fromObject(map).toString());
Copy after login
fail("==============Java Map >>> JSON Array ==================");
Copy after login
fail(JSONArray.fromObject(map).toString());
Copy after login
fail("==============Java Map >>> JSON Object==================");
Copy after login
Copy after login
fail(JSONSerializer.toJSON(map).toString());
Copy after login
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

上面的Map集合有JavaBean、String、Boolean、Integer、以及Array和js的function函数的字符串。

运行上面的程序,结果如下:


==============Java Map >>> JSON Object==================
Copy after login
{"arr":["a","b"],"A":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"int":1,
Copy after login
Copy after login
"B":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"name":"json",
Copy after login
Copy after login
Copy after login
"func":function(i){ return this.arr[i]; },"bool":true}
Copy after login
Copy after login
==============Java Map >>> JSON Array ==================
Copy after login
[{"arr":["a","b"],"A":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"int":1,
Copy after login
"B":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"name":"json",
Copy after login
Copy after login
Copy after login
"func":function(i){ return this.arr[i]; },"bool":true}]
Copy after login
==============Java Map >>> JSON Object==================
Copy after login
{"arr":["a","b"],"A":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"int":1,
Copy after login
Copy after login
"B":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"name":"json",
Copy after login
Copy after login
Copy after login
"func":function(i){ return this.arr[i]; },"bool":true}
Copy after login
Copy after login

4、 将更多类型转换成JSON


/**
Copy after login
Copy after login
Copy after login
* function: 转换更多数组类型到JSON
Copy after login
* @author hoojo
Copy after login
Copy after login
Copy after login
Copy after login
* @createDate Nov 28, 2010 2:39:19 PM
Copy after login
*/
Copy after login
Copy after login
Copy after login
Copy after login
@Test
Copy after login
Copy after login
Copy after login
Copy after login
public void writeObject2JSON() {
Copy after login
String[] sa = {"a", "b", "c"};
Copy after login
fail("==============Java StringArray >>> JSON Array ==================");
Copy after login
fail(JSONArray.fromObject(sa).toString());
Copy after login
fail(JSONSerializer.toJSON(sa).toString());
Copy after login
fail("==============Java boolean Array >>> JSON Array ==================");
Copy after login
boolean[] bo = { true, false, true };
Copy after login
fail(JSONArray.fromObject(bo).toString());
Copy after login
fail(JSONSerializer.toJSON(bo).toString());
Copy after login
Object[] o = { 1, "a", true, 'A', sa, bo };
Copy after login
fail("==============Java Object Array >>> JSON Array ==================");
Copy after login
fail(JSONArray.fromObject(o).toString());
Copy after login
fail(JSONSerializer.toJSON(o).toString());
Copy after login
fail("==============Java String >>> JSON ==================");
Copy after login
fail(JSONArray.fromObject("['json','is','easy']").toString());
Copy after login
fail(JSONObject.fromObject("{'json':'is easy'}").toString());
Copy after login
fail(JSONSerializer.toJSON("['json','is','easy']").toString());
Copy after login
fail("==============Java JSONObject >>> JSON ==================");
Copy after login
jsonObject = new JSONObject()
Copy after login
.element("string", "JSON")
Copy after login
.element("integer", "1")
Copy after login
.element("double", "2.0")
Copy after login
.element("boolean", "true");
Copy after login
fail(JSONSerializer.toJSON(jsonObject).toString());
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
fail("==============Java JSONArray >>> JSON ==================");
Copy after login
jsonArray = new JSONArray()
Copy after login
.element( "JSON" )
Copy after login
.element( "1" )
Copy after login
.element( "2.0" )
Copy after login
.element( "true" );
Copy after login
fail(JSONSerializer.toJSON(jsonArray).toString());
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
fail("==============Java JSONArray JsonConfig#setArrayMode >>> JSON ==================");
Copy after login
List input = new ArrayList();
Copy after login
input.add("JSON");
Copy after login
input.add("1");
Copy after login
input.add("2.0");
Copy after login
input.add("true");
Copy after login
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input );
Copy after login
JsonConfig jsonConfig = new JsonConfig();
Copy after login
Copy after login
jsonConfig.setArrayMode( JsonConfig.MODE_OBJECT_ARRAY );
Copy after login
Object[] output = (Object[]) JSONSerializer.toJava(jsonArray, jsonConfig);
Copy after login
System.out.println(output[0]);
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
fail("==============Java JSONFunction >>> JSON ==================");
Copy after login
String str = "{'func': function( param ){ doSomethingWithParam(param); }}";
Copy after login
JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(str);
Copy after login
JSONFunction func = (JSONFunction) jsonObject.get("func");
Copy after login
fail(func.getParams()[0]);
Copy after login
fail(func.getText() );
Copy after login
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

运行后结果如下:


==============Java StringArray >>> JSON Array ==================
Copy after login
["a","b","c"]
Copy after login
["a","b","c"]
Copy after login
==============Java boolean Array >>> JSON Array ==================
Copy after login
[true,false,true]
Copy after login
[true,false,true]
Copy after login
==============Java Object Array >>> JSON Array ==================
Copy after login
[1,"a",true,"A",["a","b","c"],[true,false,true]]
Copy after login
[1,"a",true,"A",["a","b","c"],[true,false,true]]
Copy after login
==============Java String >>> JSON ==================
Copy after login
["json","is","easy"]
Copy after login
Copy after login
{"json":"is easy"}
Copy after login
["json","is","easy"]
Copy after login
Copy after login
==============Java JSONObject >>> JSON ==================
Copy after login
{"string":"JSON","integer":"1","double":"2.0","boolean":"true"}
Copy after login
==============Java JSONArray >>> JSON ==================
Copy after login
["JSON","1","2.0","true"]
Copy after login
==============Java JSONArray JsonConfig#setArrayMode >>> JSON ==================
Copy after login
JSON
Copy after login
==============Java JSONFunction >>> JSON ==================
Copy after login
param
Copy after login
doSomethingWithParam(param);
Copy after login

这里还有一个JSONFunction的对象,可以转换JavaScript的function。可以获取方法参数和方法体。同时,还可以用JSONObject、JSONArray构建Java对象,完成Java对象到JSON字符串的转换。

三、JSON对象反序列化成Java对象

1、 将json字符串转成Java对象


private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"}," +
Copy after login
"\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
Copy after login
/**
Copy after login
* function:将json字符串转化为java对象
Copy after login
* @author hoojo
Copy after login
Copy after login
Copy after login
Copy after login
* @createDate Nov 28, 2010 3:01:16 PM
Copy after login
*/
Copy after login
Copy after login
Copy after login
Copy after login
@Test
Copy after login
Copy after login
Copy after login
Copy after login
public void readJSON2Bean() {
Copy after login
fail("==============JSON Object String >>> Java Bean ==================");
Copy after login
jsonObject = JSONObject.fromObject(json);
Copy after login
Student stu = (Student) JSONObject.toBean(jsonObject, Student.class);
Copy after login
fail(stu.toString());
Copy after login
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

运行后,结果如下:


==============JSON Object String >>> Java Bean ==================
Copy after login
tom#22#chian#2010-11-22#email@123.com
Copy after login
Copy after login
Copy after login
Copy after login

2、 将json字符串转换成动态Java对象(MorphDynaBean)


private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
Copy after login
Copy after login
Copy after login
Copy after login
"\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
Copy after login
Copy after login
Copy after login
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
@Test
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
public void readJSON2DynaBean() {
Copy after login
try {
Copy after login
Copy after login
Copy after login
Copy after login
fail("==============JSON Object String >>> Java MorphDynaBean ==================");
Copy after login
JSON jo = JSONSerializer.toJSON(json);
Copy after login
Object o = JSONSerializer.toJava(jo);//MorphDynaBean
Copy after login
fail(PropertyUtils.getProperty(o, "address").toString());
Copy after login
jsonObject = JSONObject.fromObject(json);
Copy after login
Copy after login
fail(jsonObject.getString("email"));
Copy after login
o = JSONSerializer.toJava(jsonObject);//MorphDynaBean
Copy after login
fail(PropertyUtils.getProperty(o, "name").toString());
Copy after login
} catch (IllegalAccessException e) {
Copy after login
e.printStackTrace();
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
} catch (InvocationTargetException e) {
Copy after login
e.printStackTrace();
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
} catch (NoSuchMethodException e) {
Copy after login
e.printStackTrace();
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
}
Copy after login
Copy after login
Copy after login
Copy after login
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

转换后的对象Object是一个MorphDynaBean的动态JavaBean,通过PropertyUtils可以获得指定的属性的值。

运行后结果如下:


==============JSON Object String >>> Java MorphDynaBean =============
Copy after login
chian
Copy after login
email@123.com
Copy after login
tom
Copy after login

3、 将json字符串转成Java的Array数组


private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
Copy after login
Copy after login
Copy after login
Copy after login
"\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
Copy after login
Copy after login
Copy after login
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
@Test
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
public void readJSON2Array() {
Copy after login
try {
Copy after login
Copy after login
Copy after login
Copy after login
fail("==============JSON Arry String >>> Java Array ==================");
Copy after login
json = "[" + json + "]";
Copy after login
Copy after login
Copy after login
jsonArray = JSONArray.fromObject(json);
Copy after login
Copy after login
Copy after login
fail("#%%%" + jsonArray.get(0).toString());
Copy after login
Object[] os = jsonArray.toArray();
Copy after login
System.out.println(os.length);
Copy after login

Copy after login
Copy after login
Copy after login
fail(JSONArray.fromObject(json).join(""));
Copy after login
fail(os[0].toString());
Copy after login
Student[] stus = (Student[]) JSONArray.toArray(jsonArray, Student.class);
Copy after login
System.out.println(stus.length);
Copy after login
System.out.println(stus[0]);
Copy after login
} catch (Exception e) {
Copy after login
Copy after login
Copy after login
e.printStackTrace();
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
}
Copy after login
Copy after login
Copy after login
Copy after login
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

运行的结果如下:


==============JSON Arry String >>> Java Array ==================
Copy after login
#%%%{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}
Copy after login
1
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}
Copy after login
Copy after login
{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}
Copy after login
Copy after login
1
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
tom#22#chian#2010-11-22#email@123.com
Copy after login
Copy after login
Copy after login
Copy after login

4、 将JSON字符串转成Java的List集合


private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
Copy after login
Copy after login
Copy after login
Copy after login
"\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
Copy after login
Copy after login
Copy after login
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
@Test
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
public void readJSON2List() {
Copy after login
try {
Copy after login
Copy after login
Copy after login
Copy after login
fail("==============JSON Arry String >>> Java List ==================");
Copy after login
json = "[" + json + "]";
Copy after login
Copy after login
Copy after login
jsonArray = JSONArray.fromObject(json);
Copy after login
Copy after login
Copy after login
List list = JSONArray.toList(jsonArray, Student.class);
Copy after login
System.out.println(list.size());
Copy after login
Copy after login
System.out.println(list.get(0));
Copy after login

Copy after login
Copy after login
Copy after login
list = JSONArray.toList(jsonArray);
Copy after login
System.out.println(list.size());
Copy after login
Copy after login
System.out.println(list.get(0));//MorphDynaBean
Copy after login
} catch (Exception e) {
Copy after login
Copy after login
Copy after login
e.printStackTrace();
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
}
Copy after login
Copy after login
Copy after login
Copy after login
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

运行后结果如下:


==============JSON Arry String >>> Java List ==================
Copy after login
1
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
tom#22#chian#2010-11-22#email@123.com
Copy after login
Copy after login
Copy after login
Copy after login
1
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
net.sf.ezmorph.bean.MorphDynaBean@141b571[
Copy after login
{id=22, birthday=net.sf.ezmorph.bean.MorphDynaBean@b23210[
Copy after login
{birthday=2010-11-22}
Copy after login
], address=chian, email=email@123.com, name=tom}
Copy after login
]
Copy after login

5、 将json字符串转换成Collection接口


private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
Copy after login
Copy after login
Copy after login
Copy after login
"\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
Copy after login
Copy after login
Copy after login
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
@Test
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
public void readJSON2Collection() {
Copy after login
try {
Copy after login
Copy after login
Copy after login
Copy after login
fail("==============JSON Arry String >>> Java Collection ==================");
Copy after login
json = "[" + json + "]";
Copy after login
Copy after login
Copy after login
jsonArray = JSONArray.fromObject(json);
Copy after login
Copy after login
Copy after login
Collection con = JSONArray.toCollection(jsonArray, Student.class);
Copy after login
System.out.println(con.size());
Copy after login
Object[] stt = con.toArray();
Copy after login
System.out.println(stt.length);
Copy after login
fail(stt[0].toString());
Copy after login

Copy after login
Copy after login
Copy after login
} catch (Exception e) {
Copy after login
e.printStackTrace();
Copy after login
}
Copy after login
}
Copy after login
Copy after login
Copy after login

刚才上面的将json转换成list提示该方法过时,这里有toCollection,可以用此方法代替toList方法;运行后结果如下:


==============JSON Arry String >>> Java Collection ==================
Copy after login
1
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
1
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
tom#22#chian#2010-11-22#email@123.com
Copy after login
Copy after login
Copy after login
Copy after login

6、 将json字符串转换成Map集合


@Test
Copy after login
Copy after login
public void readJSON2Map() {
Copy after login
try {
Copy after login
fail("==============JSON Arry String >>> Java Map ==================");
Copy after login
json = "{\"arr\":[\"a\",\"b\"],\"A\":{\"address\":\"address\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
Copy after login
"\"email\":\"email\",\"id\":1,\"name\":\"jack\"},\"int\":1,"+
Copy after login
"\"B\":{\"address\":\"address\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
Copy after login
"\"email\":\"email\",\"id\":1,\"name\":\"jack\"},\"name\":\"json\",\"bool\":true}";
Copy after login
jsonObject = JSONObject.fromObject(json);
Copy after login
Copy after login
Map> clazzMap = new HashMap>();
Copy after login
clazzMap.put("arr", String[].class);
Copy after login
clazzMap.put("A", Student.class);
Copy after login
clazzMap.put("B", Student.class);
Copy after login
Map mapBean = (Map) JSONObject.toBean(jsonObject, Map.class, clazzMap);
Copy after login
System.out.println(mapBean);
Copy after login

Copy after login
Set set = mapBean.keySet();
Copy after login
Iterator iter = set.iterator();
Copy after login
while (iter.hasNext()) {
Copy after login
String key = iter.next();
Copy after login
fail(key + ":" + mapBean.get(key).toString());
Copy after login
}
Copy after login
} catch (Exception e) {
Copy after login
Copy after login
Copy after login
e.printStackTrace();
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
}
Copy after login
Copy after login
Copy after login
Copy after login
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

运行后结果如下:


==============JSON Arry String >>> Java Map ==================
Copy after login
{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}
Copy after login
A:jack#1#address#2010-11-22#email
Copy after login
arr:[a, b]
Copy after login
B:jack#1#address#2010-11-22#email
Copy after login
int:1
Copy after login
name:json
Copy after login
bool:true
Copy after login

四、JSON-libXML的支持

1、 将Java对象到XML


/*============================Java Object >>>>> XML ==========================*/
Copy after login
/**
Copy after login
Copy after login
* function: 转换Java对象到XML
Copy after login
* 需要额外的jar包:xom.jar
Copy after login
* @author hoojo
Copy after login
* @createDate Nov 28, 2010 2:39:55 PM
Copy after login
*/
Copy after login
@Test
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
public void writeObject2XML() {
Copy after login
XMLSerializer xmlSerializer = new XMLSerializer();
Copy after login
fail("==============Java String Array >>> XML ==================");
Copy after login
Copy after login
//xmlSerializer.setElementName("bean");
Copy after login
fail(xmlSerializer.write(JSONArray.fromObject(bean)));
Copy after login
String[] sa = {"a", "b", "c"};
Copy after login
fail("==============Java String Array >>> XML ==================");
Copy after login
Copy after login
fail(xmlSerializer.write(JSONArray.fromObject(sa)));
Copy after login
fail("==============Java boolean Array >>> XML ==================");
Copy after login
boolean[] bo = { true, false, true };
Copy after login
fail(xmlSerializer.write(JSONArray.fromObject(bo)));
Copy after login
fail(xmlSerializer.write(JSONSerializer.toJSON(bo)));
Copy after login
Object[] o = { 1, "a", true, 'A', sa, bo };
Copy after login
Copy after login
fail("==============Java Object Array >>> JSON Array ==================");
Copy after login
Copy after login
fail(xmlSerializer.write(JSONArray.fromObject(o)));
Copy after login
fail(xmlSerializer.write(JSONSerializer.toJSON(o)));
Copy after login
fail("==============Java String >>> JSON ==================");
Copy after login
Copy after login
fail(xmlSerializer.write(JSONArray.fromObject("['json','is','easy']")).toString());
Copy after login
fail(xmlSerializer.write(JSONObject.fromObject("{'json':'is easy'}")).toString());
Copy after login
fail(xmlSerializer.write(JSONSerializer.toJSON("['json','is','easy']")).toString());
Copy after login
}
Copy after login
Copy after login
Copy after login

主要运用的是XMLSerializer的write方法,这个方法可以完成java对象到xml的转换,不过你很容易就可以看到这个xml序列化对象,需要先将java对象转成json对象,然后再将json转换吃xml文档。

运行后结果如下:

==============Java String Array >>> XML ==================   
address
2010-11-22 email1haha
==============Java String Array >>> XML ================== abc ==============Java boolean Array >>> XML ================== truefalsetrue truefalsetrue ==============Java Object Array >>> JSON Array ================== 1atrueA abctrue falsetrue 1atrueA abctrue falsetrue ==============Java String >>> JSON ================== jsoniseasy is easy jsoniseasy
Copy after login

上面的节点名称有点乱,你可以通过setElementName设置节点名称

2、 将XML转换成Java对象


/*============================XML String >>>>> Java Object ==========================*/
Copy after login
/**
Copy after login
Copy after login
* function:转换xml文档到java对象
Copy after login
* @author hoojo
Copy after login
* @createDate Nov 28, 2010 3:00:27 PM
Copy after login
*/
Copy after login
@Test
Copy after login
public void readXML2Object() {
Copy after login
XMLSerializer xmlSerializer = new XMLSerializer();
Copy after login
fail("============== XML >>>> Java String Array ==================");
Copy after login
String[] sa = {"a", "b", "c"};
Copy after login
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONArray.fromObject(sa)));
Copy after login
fail(jsonArray.toString());
Copy after login

Copy after login
Copy after login
Copy after login
String[] s = (String[]) JSONArray.toArray(jsonArray, String.class);
Copy after login
fail(s[0].toString());
Copy after login
Copy after login

Copy after login
Copy after login
fail("============== XML >>>> Java boolean Array ==================");
Copy after login
boolean[] bo = { true, false, true };
Copy after login
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONArray.fromObject(bo)));
Copy after login
bo = (boolean[]) JSONArray.toArray(jsonArray, boolean.class);
Copy after login
fail(bo.toString());
Copy after login
System.out.println(bo[0]);
Copy after login

Copy after login
Copy after login
Copy after login
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONSerializer.toJSON(bo)));
Copy after login
bo = (boolean[]) JSONArray.toArray(jsonArray, boolean.class);
Copy after login
fail(bo.toString());
Copy after login
System.out.println(bo[0]);
Copy after login

Copy after login
Copy after login
fail("==============Java Object Array >>> JSON Array ==================");
Copy after login
Copy after login
Object[] o = { 1, "a", true, 'A', sa, bo };
Copy after login
Copy after login
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONArray.fromObject(o)));
Copy after login
System.out.println(jsonArray.getInt(0));
Copy after login
System.out.println(jsonArray.get(1));
Copy after login
System.out.println(jsonArray.getBoolean(2));
Copy after login
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONSerializer.toJSON(o)));
Copy after login
System.out.println(jsonArray.get(4));
Copy after login
System.out.println(jsonArray.getJSONArray(5).get(0));
Copy after login
System.out.println(jsonArray.get(5));
Copy after login

Copy after login
Copy after login
Copy after login
fail("==============Java String >>> JSON ==================");
Copy after login
Copy after login
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONArray.fromObject("['json','is','easy']")).toString());
Copy after login
s = (String[]) JSONArray.toArray(jsonArray, String.class);
Copy after login
Copy after login
fail(s[0].toString());
Copy after login
Copy after login
jsonObject = (JSONObject) xmlSerializer.read(xmlSerializer.write(JSONObject.fromObject("{'json':'is easy'}")).toString());
Copy after login
Object obj = JSONObject.toBean(jsonObject);
Copy after login
System.out.println(obj);
Copy after login
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONSerializer.toJSON("['json','is','easy']")).toString());
Copy after login
s = (String[]) JSONArray.toArray(jsonArray, String.class);
Copy after login
Copy after login
fail(s[1].toString());
Copy after login
}
Copy after login
Copy after login
Copy after login

主要运用到XMLSerializer的read方法,将xml内容读取后,转换成Java对象。运行后结果如下:


============== XML >>>> Java String Array ==================
Copy after login
["a","b","c"]
Copy after login
a
Copy after login
Copy after login
============== XML >>>> Java boolean Array ==================
Copy after login
[Z@15856a5
Copy after login
true
Copy after login
Copy after login
Copy after login
Copy after login
[Z@79ed7f
Copy after login
true
Copy after login
Copy after login
Copy after login
Copy after login
==============Java Object Array >>> JSON Array ==================
Copy after login
1
Copy after login
a
Copy after login
Copy after login
true
Copy after login
Copy after login
Copy after login
Copy after login
["a","b","c"]
Copy after login
true
Copy after login
Copy after login
Copy after login
Copy after login
["true","false","true"]
Copy after login
==============Java String >>> JSON ==================
Copy after login
json
Copy after login
net.sf.ezmorph.bean.MorphDynaBean@c09554[
Copy after login
{json=is easy}
Copy after login
]
Copy after login
is
Copy after login

3、 将xml的字符串内容,转换成Java的Array对象


@Test
Copy after login
Copy after login
public void testReadXml2Array() {
Copy after login
String str = "" +
Copy after login
"" +
Copy after login
"return matrix[i][j];" +
Copy after login
"" +
Copy after login
"";
Copy after login
JSONArray json = (JSONArray) new XMLSerializer().read(str);
Copy after login
fail(json.toString());
Copy after login
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

上面是一段xml字符串格式的文档,将其转换为JSONArray对象。转换后结果如下:


[function(i,j){ return matrix[i][j]; }]
Copy after login

就是一个数组;

以上就是JSON-lib框架,转换JSON、XML不再困难的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!