随笔-9  评论-168  文章-266  trackbacks-0

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

一、 准备工作 

 

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

下载地址:

目前最新的是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

官方网址:

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

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

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

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

如果你还不了解json是什么?那么你应该可以看看

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;
 
/**
 * function: 用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方面的知识,请看:

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

二、 java对象序列化成json对象

1、 将javaobject转换吃json字符串

在jsonlibtest中添加如下代码:

/*=========================java object >>>> json string ===========================*/
/**
 * function:转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%%�dress--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字符串

/**
 * function:转换java list集合到json
 * @author hoojo
 * @createdate nov 28, 2010 2:36:15 pm
 */
@test
public void writelist2json() {
    fail("==============java list >>> json array==================");
    list stu = new arraylist();
    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对象

/**
 * function:转java map对象到json
 * @author hoojo
 * @createdate nov 28, 2010 2:37:35 pm
 */
@test
public void writemap2json() {
    map map = new hashmap();
    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

/**
 * function:  转换更多数组类型到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\"}";
/**
 * function:将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 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 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> clazzmap = new hashmap>();
        clazzmap.put("arr", string[].class);
        clazzmap.put("a", student.class);
        clazzmap.put("b", student.class);
        map mapbean = (map) jsonobject.tobean(jsonobject, map.class, clazzmap);
        system.out.println(mapbean);
        
        set set = mapbean.keyset();
        iterator 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-libxml的支持

1、 将java对象到xml

/*============================java object >>>>> xml ==========================*/
/**
 * function: 转换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">addressaddress><birthday class="object"><birthday type="string">2010-11-22birthday>birthday>
<email type="string">emailemail><id type="number">1id><name type="string">hahaname>
e>a>
 
==============java string array >>> xml ==================
xml version="1.0" encoding="utf-8"?>
<a><e type="string">ae><e type="string">be><e type="string">ce>a>
 
==============java boolean array >>> xml ==================
xml version="1.0" encoding="utf-8"?>
<a><e type="boolean">truee><e type="boolean">falsee><e type="boolean">truee>a>
 
xml version="1.0" encoding="utf-8"?>
<a><e type="boolean">truee><e type="boolean">falsee><e type="boolean">truee>a>
 
==============java object array >>> json array ==================
xml version="1.0" encoding="utf-8"?>
<a><e type="number">1e><e type="string">ae><e type="boolean">truee><e type="string">ae><e class="array">
<e type="string">ae><e type="string">be><e type="string">ce>e><e class="array"><e type="boolean">truee>
<e type="boolean">falsee><e type="boolean">truee>e>a>
 
xml version="1.0" encoding="utf-8"?>
<a><e type="number">1e><e type="string">ae><e type="boolean">truee><e type="string">ae><e class="array">
<e type="string">ae><e type="string">be><e type="string">ce>e><e class="array"><e type="boolean">truee>
<e type="boolean">falsee><e type="boolean">truee>e>a>
 
==============java string >>> json ==================
xml version="1.0" encoding="utf-8"?>
<a><e type="string">jsone><e type="string">ise><e type="string">easye>a>
 
xml version="1.0" encoding="utf-8"?>
<o><json type="string">is easyjson>o>
 
xml version="1.0" encoding="utf-8"?>
<a><e type="string">jsone><e type="string">ise><e type="string">easye>a>

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

2、 将xml转换成java对象

/*============================xml string >>>>> java object ==========================*/
/**
 * function:转换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 = "
";
    jsonarray json = (jsonarray) new xmlserializer().read(str);
    fail(json.tostring());   
}

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

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

就是一个数组;

posted on 2012-02-23 10:56 紫蝶∏飛揚↗ 阅读(1559) 评论(0)  编辑  收藏 所属分类: json

只有注册用户后才能发表评论。


网站导航:
              
 
网站地图