qianqianxiao 2012-12-06
Json-lib使用——JSONObject与JSONArray
1.从Object到String
要先用Object对象构造一个JSONObject或者JSONArray对象,然后调用它的toString()方法即可
(1)示例一
1Bookbook=newBook();
2book.setName("Java");
3book.setPrice(52.3f);
4JSONObjectobject=JSONObject.fromObject(book);
5System.out.println(object.toString());
(2)示例二
复制代码
1Bookbook=newBook();
2book.setName("Java");
3book.setPrice(52.3f);
4
5Bookbook2=newBook();
6book2.setName("C");
7book2.setPrice(42.3f);
8Listlist=newArrayList();
9list.add(book);
10list.add(book2);
11JSONArrayarry=JSONArray.fromObject(list);
12System.out.println(arry.toString());
13//结果如下:
14[{"name":"Java","price":52.3},{"name":"C","price":42.3}]
复制代码
2.从String到Object
要先用String对象构造一个JSONObject或者JSONArray对象
(1)示例一
1Stringjson="{name:'Java',price:52.3}";
2JSONObjectobject=JSONObject.fromObject(json);
3System.out.println(object.get("name")+""+object.get("price"));
(2)示例二
复制代码
1Stringjson="[{name:'Java',price:52.3},{name:'C',price:42.3}]";
2JSONArrayarray=JSONArray.fromObject(json);
3for(inti=0;i<array.size();i++){
4Mapo=(Map)array.get(i);
5System.out.println(o.get("name")+""+o.get("price"));
6}
复制代码
3.从String到Bean
(1)单个Bean对象
1Stringjson="{name:'Java',price:52.3}";
2JSONObjectobject=JSONObject.fromObject(json);
3Productproduct=(Product)JSONObject.toBean(object,Product.class);
4System.out.println(product.getName()+""+product.getPrice());
(2).Bean的数组
复制代码
1Stringjson="[{name:'Java',price:52.3},{name:'C',price:42.3}]";
2JSONArrayarray=JSONArray.fromObject(json);
3Product[]products=(Product[])JSONArray.toArray(array,Product.class);
4for(Productp:products){
5System.out.println(p.getName()+""+p.getPrice());
6}
复制代码
自定义封装JSON操作的类
复制代码
1packagecom.util;
2
3importjava.util.List;
4importjava.util.Map;
5
6importnet.sf.json.JSONArray;
7importnet.sf.json.JSONObject;
8
9publicclassJsonHelper{
10//从普通的Bean转换为字符串
11publicstaticStringgetJson(Objecto){
12JSONObjectjo=JSONObject.fromObject(o);
13returnjo.toString();
14}
15//从Java的列表转换为字符串
16publicstaticStringgetJson(Listlist){
17JSONArrayja=JSONArray.fromObject(list);
18returnja.toString();
19}
20//从Java对象数组转换为字符串
21publicstaticStringgetJson(Object[]arry){
22JSONArrayja=JSONArray.fromObject(arry);
23returnja.toString();
24}
25//从json格式的字符串转换为Map对象
26publicstaticMapgetObject(Strings){
27returnJSONObject.fromObject(s);
28}
29//从json格式的字符串转换为List数组
30publicstaticListgetArray(Strings){
31returnJSONArray.fromObject(s);
32}
33//从json格式的字符串转换为某个Bean
34publicstaticObjectgetObject(Strings,Classcls){
35JSONObjectjo=JSONObject.fromObject(s);
36returnJSONObject.toBean(jo,cls);
37}
38//从json格式的字符串转换为某类对象的数组
39publicstaticObjectgetArray(Strings,Classcls){
40JSONArrayja=JSONArray.fromObject(s);
41returnJSONArray.toArray(ja,cls);
42}
43}