json-lib demo
JSON-lib这个Java类包用于把bean,map和XML转换成JSON并能够把JSON转回成bean和DynaBean。
到http://json-lib.sourceforge.net下载json-lib-1.1-jdk15.jar,运行json还需要的包有:
jakarta commons-lang 2.4.jar
jakarta commons-beanutils 1.7.0.jar
jakarta commons-collections 3.2.jar
jakarta commons-logging 1.1.1.jar
ezmorph 1.0.6.jar
可在http://www.docjar.com上搜索下载。
javaScript与java对象之间的对应关系
string | <=> | java.lang.String, java.lang.Character, char |
number | <=> | java.lang.Number, byte, short, int, long, float, double |
true|false | <=> | java.lang.Boolean, boolean |
null | <=> | null |
function | <=> | net.sf.json.JSONFunction |
array | <=> | net.sf.json.JSONArray (object, string, number, boolean, function) |
object | <=> | net.sf.json.JSONObject |
1. 将java数组和java集合转化成一个json数组
通过静态工厂方法JSONArray.fromObject()将一个java数组或集合转化成一个json数组对象JSONArray.
实例1:转化java数组
String [] array = {"a","d","1","b"}; JSONArray jsonArray = JSONArray.fromObject(array); System.out.println(jsonArray);
输出结果:["a","d","1","b"]//注意他们的顺序与java数组中的顺序是一致的。
实例2:转化List对象
String [] array = {"d","a","1","b"}; List list = new ArrayList(); list.add( array ); list.add( "second element"); JSONArray jsonArray = JSONArray.fromObject(list); System.out.println(jsonArray);
输出结果:[["d","a","1","b"],"second element"]
实例3:转化字符串
String test = "['json','is','easy']"; JSONArray jsonArray = JSONArray.fromObject( test ); System.out.println(jsonArray);
使用JSONArray.fromObject()转化字符串时,字符串必须符合JSONArray的格式。
2.将Map或javaBean转化成JSONObject
实例4:转化Map
Map map = new HashMap(); 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];}"); JSONObject json = JSONObject.fromObject(map); System.out.println(json);
输出:[“name”: “json”, “bool”:true, “int”,1, “arr”:[ “a”, “b”], “func”:function(i){return this.arr[i];}]
实例5:转化javaBean
public class TestBean { private String id; private String name; private int age; private String email; public TestBean() { } public TestBean(String id, String name, int age, String email) { super(); this.id = id; this.name = name; this.age = age; this.email = email; } //以下为get、set方法 }
输出:{"age":36,"email":"","id":"2","name":"xxhh"}
//这是一个json object,其实就是一个javascript对象。注意其中属性的顺序,是排过序的。
3.将JSONObject转化为javaBean对象
实例6:
String myJson = "{'age':36,'email':'','id':'2','name':'testName'}"; JSONObject jsonObject1 = JSONObject.fromObject( myJson ); TestBean bean = (TestBean) JSONObject.toBean( jsonObject1, TestBean.class ); System.out.println("beanName:" + bean.getName());
输出:beanName:testName
4.将JSONArray转化为list对象:
实例7:
ExampleBean对象的代码如下:
public class ExampleBean { private String name; private String id; private int age; public ExampleBean() { super(); } public ExampleBean(String name, String id, int age) { super(); this.name = name; this.id = id; this.age = age; } //getter和setter方法 }
测试代码:
public class Test { public static void main(String[] args) { List<ExampleBean> list1 = new ArrayList<ExampleBean>(); for (int i = 0; i < 5; i++) { String name = "xxlong" + i; int age = 20 + i; ExampleBean bean = new ExampleBean(name, i + "", age); list1.add(bean); } JSONArray jsonArray = JSONArray.fromObject(list1); System.out.println("list1:" + list1); List<ExampleBean> list2 = JSONArray .toList(jsonArray, ExampleBean.class); System.out.println("list2:" + list2); List<ExampleBean> list3 = JSONArray .toList(jsonArray); System.out.println("list3:" + list3); } }
输出结果如下所示:
list1:[ExampleBean@13a328f, ExampleBean@1cd8669, ExampleBean@337838, ExampleBean@119cca4, ExampleBean@ca2dce]
list2:[ExampleBean@765291, ExampleBean@26e431, ExampleBean@14f8dab, ExampleBean@1ddebc3, ExampleBean@a18aa2]
list3:[net.sf.ezmorph.bean.MorphDynaBean@17182c1[
{id=0, age=20, name=xxlong0}
], net.sf.ezmorph.bean.MorphDynaBean@13f5d07[
{id=1, age=21, name=xxlong1}
], net.sf.ezmorph.bean.MorphDynaBean@f4a24a[
{id=2, age=22, name=xxlong2}
], net.sf.ezmorph.bean.MorphDynaBean@cac268[
{id=3, age=23, name=xxlong3}
], net.sf.ezmorph.bean.MorphDynaBean@1a16869[
{id=4, age=24, name=xxlong4}
]]
5.通过 Servlet 或 MVC 框架输出 JSON 时,需要设置正确的 MIME 类型(application/json)和字符编码。假定服务器使用 UTF-8 编码,则可以使用以下代码输出编码后的 JSON 文本:
response.setContentType("application/json;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.print(jsonObject); out.flush(); out.close();
6.在前台处理jsonobject:
var json = {"customerGroupList": [{"id":{"customerGroupId":1,"languageId":1},"lastModified":null,"name":"medium level","priceId":1}, {"id":{"customerGroupId":2,"languageId":1},"lastModified":null,"name":"medium level2","priceId":1}, {"id":{"customerGroupId":3,"languageId":1},"lastModified":null,"name":"level3","priceId":1}], "searchResultList":[{"custAddress":"1 Way Street,NeverNever,,PostCode1","custFirstName":"Andy","custLastLogon":"19/01/2010","custLastName":"Admin","custlogons":25}, {"custAddress":"3 Way Street,NeverNever,,PostCode3","custFirstName":"Olly","custLastLogon":"18/12/2009","custLastName":"Order","custlogons":0}, {"custAddress":"1 Way Street,NeverNever,,12345","custFirstName":"John","custLastLogon":"18/12/2009","custLastName":"Doe","custlogons":0}, {"custAddress":"2 Way Street,NeverNever,,PostCode2","custFirstName":"Caty","custLastLogon":"18/12/2009","custLastName":"Catalog","custlogons":0}]};
这是一个非常复杂的jsonobject对象.在后台,它是将一个个CustomerGroup对象和CustomerSearchResult对象分别存入的ArrayList中,然后再以customerGroupList和searchResultList为key存入HashMap中,最后转化为jsonobject对象传递到前台.在前台进行处理时,你可以把它看成一个变通地js对象,然后使用属性访问来得到它对应的属性值.
如:
//就可以得到一个js数组对象,即json对象的前面一部分.即用[]括隹的那个对象. var custGroupList = json.customerGroupList; //同样.它也是得到一个js数组对象 var array2 = json.searchResultList; for(var i = 0 ; i < array2.length; i++){ //得到array中的每一个对象 var cust = array[i]; var result = ""; //得到每一个对象的属性及属性值,当然也可以使用Object.attributeName.这 种方式得到对象的属性值,根据个人喜好 for(var attrName in cust){ result = "attribute name = " + attrName + "and attribute value = " + cust[attrName]; } }
再如,你从后以会了一个如下所示的json对象,它在后台其实是一个map对象:
var mapping = {"B202":["B202","B402","B502","B702"],"B201":["B201","B401","B501","B701"],"B103":["B103","B403","B503","B703"],"B703":["B703"]}
这时,比如你要取得B202的映射,你可以使用期mapping.B202,你得到的结果就是B202相对应的值,即:
["B202","B402","B502","B702"]
这在js中是一个数组,它具有数组具有的一切功能,它在后台中是java的一个list对象.如果你要动态的取值,比如传过来一个id,这个id可以是B202,B201或B103等等,比如,传进来的id=B202,这时,你就不能用mapping.id取值了,这样的话,它会去取mapping这个json对象中id属性这个值,而mapping对象中没有id这个属性,所有返回给你的是一个undefined,你应该使用mapping[id]这种方法来动态取值,这时它就会正确的返回结果:
["B202","B402","B502","B702"]
7.有关boolean值
如果你的Bean中有boolean属性值的话,你要注意boolean属性值的命名,如果你使用is开头,如isSucc,然后又是用eclipse生成它的setter和getter方法时,你就会遇到意想不到麻烦,因为你的setter方法不再是setIsSucc,而是setSucc,所以转化成Bean时它就会有问题
看例子:TestBoolean类代码如下所示:
public class TestBoolean { private boolean isSucc; private String msg; public TestBoolean() { super(); // TODO Auto-generated constructor stub } public TestBoolean(boolean isSucc, String msg) { super(); this.isSucc = isSucc; this.msg = msg; } public boolean isSucc() { return isSucc; } public void setSucc(boolean isSucc) { this.isSucc = isSucc; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
注意TestBoolean中属性isSucc的setter方法。
测试方法如下所示:
@Test public void test() { String json = "{isSucc: true,msg: 'This is msg property!'}"; JSONObject jsonObj = JSONObject.fromObject( json ); TestBoolean bean = (TestBoolean)JSONObject.toBean( jsonObj, TestBoolean.class ); System.out.println(bean.isSucc()); assertEquals(true, bean.isSucc()); }
这时junit测试会通不过,报告一个failure,同进控制台打印出了false. 这是因为TestBoolean这个类属性isSucc的setter方法并不是setIsSucc,而是setIsSucc,所以转化Bean时,它会根据你传入的属性名是isSucc,值是true;所以它会去查询setIsSucc方法给isSucc赋值,它没有找到setIsSucc这个方法,所以就没法给isSucc赋值;如果你将你的json对象改成succ:true;再进行测试,此测试就会成功了,并且控制台打印出了true。如下所示:
String json = "{succ: true,msg: 'This is msg property!'}";
或者你不修改json字符串,你可以只修改isSucc属性的setter方法,改成setIsSucc,测试程序同样可以运行成功。
你将TestBoolean中的boolean属性改成Boolean,效果将是一样的。如下所示:
public class TestBoolean { private Boolean succ; private String msg; public TestBoolean() { super(); // TODO Auto-generated constructor stub } public TestBoolean(Boolean succ, String msg) { super(); this.succ = succ; this.msg = msg; } public Boolean getSucc() { return succ; } public void setSucc(Boolean succ) { this.succ = succ; } ...... }
测试程序还是像上面所示,只是将json字符串修改成
String json = "{succ: true,msg: 'This is msg property!'}";