下载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对象:这三个对象很简单我就懒得加注释了。。。
public class T2 { private String aaa = "testAAA"; private String bbb = "testBBB"; public String getAaa() { return this.aaa; } public void setAaa(String aaa) { this.aaa = aaa; } public String getBbb() { return this.bbb; } public void setBbb(String bbb) { this.bbb = bbb; } }
public class T3 { private String aaa = "testAAA"; private String ccc = "testBBB"; public String getAaa() { return this.aaa; } public void setAaa(String aaa) { this.aaa = aaa; } public String getCcc() { return this.ccc; } public void setCcc(String bbb) { this.ccc = bbb; } }
import java.util.ArrayList; import java.util.List; public class T { private String str = "testStr"; private int age = 15; private List
简单的测试代码:
import java.util.List; import net.sf.json.JSONObject; public class Test { public static void main(String[] args) throws Exception { JSONObject jo = JSONObject.fromObject(new T()); String str = (jo.toString()); System.out.println(str); JSONObject jo2 = JSONObject.fromObject(str); T t = (T) JSONObject.toBean(jo2, T.class); List
运行结果:
{"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
中华人民共和国
中华人民共和国
中华人民共和国