JSON与JAVA数据的相互转换(基本应用)

下载json及其依赖包:

jsonXXX.jar:http://sourceforge.net/projects/json-lib/files/

ezmorph-1.0.1.jar http://ezmorph.sourceforge.net/

以下的包都能在apache的官网上下载。
commons-beanutils.jar
commons-httpclient.jar
commons-lang.jar
commons-logging.jar

我下载的都是最新版本(最新版的json与其它版本有所不同)

一、将任意的javaBean对象转换为json字符串:

Object obj=XXX;//任意一个javabean的对象都可以,但是这个javaBean必须是公开的,否则会报找不到get方法。

JSONObject jo=JSONObject.fromObject(obj);

  System.out.println(jo.toString());

如果你的obj知道具体类型的话,还[可以使用JSONArray等对象来转换。其方法也类似。

二、将json字符串转换为javaBean对象:

String str="json字符串对象";

JSONObject jo=JSONObject.fromObject(obj);

T t=(T)JSONObject.toBean(jo,T.class);

XXXX

实例:

三个javabean对象:这三个对象很简单我就懒得加注释了。。。

简单的测试代码:

运行结果:

{"test2":[{"aaa":"testAAA","bbb":"testBBB"},{"aaa":"testAAA","bbb":"testBBB"},{"aaa":"testAAA","bbb":"testBBB"},{"aaa":"testAAA","bbb":"testBBB"},{"aaa":"testAAA","bbb":"testBBB"}],"age":15,"listString":["中华人民共和国","中华人民共和国","中华人民共和国"],"str":"testStr"}
testAAA
2010-5-1 0:41:50 net.sf.json.JSONObject toBean
警告: Tried to assign property bbb:java.lang.String to bean of class T3
2010-5-1 0:41:50 net.sf.json.JSONObject toBean
警告: Tried to assign property bbb:java.lang.String to bean of class T3
testAAA
2010-5-1 0:41:50 net.sf.json.JSONObject toBean
警告: Tried to assign property bbb:java.lang.String to bean of class T3
testAAA
2010-5-1 0:41:50 net.sf.json.JSONObject toBean
警告: Tried to assign property bbb:java.lang.String to bean of class T3
testAAA
2010-5-1 0:41:50 net.sf.json.JSONObject toBean
警告: Tried to assign property bbb:java.lang.String to bean of class T3
testAAA
中华人民共和国
中华人民共和国
中华人民共和国

猜你喜欢

转载自lianggeblog.iteye.com/blog/1697990