使用 net.sf.json.JSONObject;進行JSONObject、JSONArray、Map、JavaBean的相互轉換

1,JSONObjecthtml

  json對象,就是一個鍵對應一個值,使用的是大括號{ },如:{key:value}java

2,JSONArrayjson

  json數組,使用中括號[ ],只不過數組裏面的項也是json鍵值對格式的數組

  Json對象中添加的是鍵值對,JSONArray中添加的是Json對象spa

 1 import net.sf.json.JSONArray;
 2 import net.sf.json.JSONObject;
 3 import org.junit.Test;
 4 
 5 import java.util.ArrayList;
 6 import java.util.HashMap;
 7 import java.util.Iterator;
 8 
 9 public class JsonTest {
10 
11     public static void main(String[] args) {
12         //----------------JsonObject建立的方法-----------------------------------------------------------
13         //建立JsonObject第一種方法
14         JSONObject jsonObject = new JSONObject();
15         jsonObject.put("UserName", "kobi");
16         jsonObject.put("age", "34");
17         jsonObject.put("workIn", "ALI");//此處的"ALI"也能夠替換爲一個json{"sex":"男","station":"徐州","hoobey":"coding"}
18         // System.out.println("jsonObject1:" + jsonObject);//jsonObject1:{"UserName":"kobi","workIn":"ALI","age":"34"}
19         Iterator iterator = jsonObject.keys();//用Iterator迭代器遍歷取值,建議用反射機制解析到封裝好的對象中
20         while (iterator.hasNext()) {
21             String key = (String) iterator.next();
22             String value = jsonObject.getString(key);
23             System.out.println(value);//輸出值   kobi ALI 34
24         }
25         //建立JsonObject第二種方法
26         HashMap<String, String> hashMap = new HashMap<String, String>();
27         hashMap.put("UserName", "ZHULI");
28         hashMap.put("age", "30");
29         hashMap.put("workIn", "ALI");
30         // System.out.println("jsonObject2:" + JSONObject.fromObject(hashMap));//jsonObject2:{"UserName":"ZHULI","workIn":"ALI","age":"30"}
31 
32 
33         //----------------JSONArray建立的方法-----------------------------------------------------------
34         //一:遍歷JsonArray
35         String str = "[{name:'a',value:'aa'},{name:'b',value:'bb'},{name:'c',value:'cc'},{name:'d',value:'dd'}]";  // 一個未轉化的字符串
36         JSONArray json = JSONArray.fromObject(str); // 首先把字符串轉成 JSONArray  對象
37         if (json.length() > 0) {
38             for (int i = 0; i < json.length(); i++) {
39                 JSONObject job = json.getJSONObject(i);  // 遍歷 jsonarray 數組,把每個對象轉成 json 對象
40                 // System.out.println(job);//{"name":"a","value":"aa"}  {"name":"b","value":"bb"} {"name":"c","value":"cc"}.....
41                 //  System.out.println(job.get("name"));  // a b c d
42 
43             }
44         }
45 
46         //建立JsonArray方法2
47         ArrayList<String> arrayList = new ArrayList<String>();
48         arrayList.add("kobi");
49         arrayList.add("34");
50         arrayList.add("ALI");
51         //System.out.println("jsonArray2:" + JSONArray.fromObject(arrayList));//jsonArray2:["kobi","34","ALI"]
52 
53 
54     }
55 
56     @Test
57     public void test0105() {
58         /*
59 取出name4值過程步驟:  1.將以上字符串轉成JSONArray對象  2.取出對象的第一項,JSONObject 3.取出name1的值JSONObject
60                       4.而後取出name2的值JSONObject對象  5.取出name4的值value2
61 * */
62         /*  記住":"前是鍵,符號後是值  大括號成對找  一層層撥開就清楚了*/
63         String str = "[{name1:{name2:{name3:'value1',name4:'value2'}}},{}]";
64 
65         JSONArray jsonArray = JSONArray.fromObject(str);//  將結果轉成JSONArray對象的形式
66 
67         JSONObject getJsonObj = jsonArray.getJSONObject(0);//獲取json數組中的第一項
68 
69         JSONObject json = getJsonObj.getJSONObject("name1").getJSONObject("name2");//{"name4":"value2","name3":"value1"}
70         Object value = json.get("name4");
71         System.out.println(value);//value2
72     }
73 
74     @Test
75     public void test01051() {
76         JSONObject json = new JSONObject();
77         JSONArray jsonArray = new JSONArray();
78 
79         json.put("key", "value");//JSONObject對象中添加鍵值對
80         jsonArray.put(json);//將JSONObject對象添加到Json數組中
81 
82 
83         System.out.println(json);
84         System.out.println(jsonArray);
85     }
86 
87 }

 

相互轉換的方法以下,能夠運用到平常的工做中去:code

  1 package com.suning.crawler.util;
  2 
  3 import net.sf.json.JSONObject;
  4 import sun.security.util.Password;
  5 
  6 import java.lang.reflect.Method;
  7 import java.text.ParseException;
  8 import java.util.HashMap;
  9 import java.util.Iterator;
 10 import java.util.Map;
 11 
 12 /**
 13  * @Author: hoobey
 14  * @Description:
 15  * @Date: Created in 9:12 2018/1/6
 16  * @Modified By:
 17  * *轉換器
 18  * 1:將JavaBean 轉換成Map、JSONObject
 19  * 2:將JSONObject 轉換成Map
 20  */
 21 public class BeanConverter {
 22     /**
 23      * 將javaBean轉換成Map
 24      *
 25      * @param javaBean javaBean
 26      * @return Map對象
 27      */
 28     public static Map<String, String> BeantoMap(Object javaBean) {
 29         Map<String, String> result = new HashMap<String, String>();
 30         Method[] methods = javaBean.getClass().getDeclaredMethods();
 31 
 32         for (Method method : methods) {
 33             try {
 34                 if (method.getName().startsWith("get")) {
 35                     String field = method.getName();//getName  getPassword
 36                     field = field.substring(field.indexOf("get") + 3);//Name  Password
 37                     field = field.toLowerCase().charAt(0) + field.substring(1);//name password
 38                     Object value = method.invoke(javaBean, (Object[]) null);
 39                     result.put(field, null == value ? "" : value.toString());
 40                 }
 41             } catch (Exception e) {
 42             }
 43         }
 44 
 45         return result;
 46     }
 47 
 48     /**
 49      * 將json對象轉換成Map
 50      *
 51      * @param jsonObject json對象
 52      * @return Map對象
 53      */
 54     @SuppressWarnings("unchecked")
 55     public static Map<String, String> JsontoMap(JSONObject jsonObject) {
 56         Map<String, String> result = new HashMap<String, String>();
 57         Iterator<String> iterator = jsonObject.keys();
 58         String key = null;
 59         String value = null;
 60         while (iterator.hasNext()) {
 61             key = iterator.next();
 62             value = jsonObject.getString(key);
 63             result.put(key, value);
 64         }
 65         return result;
 66     }
 67 
 68     /**
 69      * 將javaBean轉換成JSONObject
 70      *
 71      * @param bean javaBean
 72      * @return json對象
 73      */
 74     public static JSONObject toJSON(Object bean) {
 75         return new JSONObject(BeantoMap(bean));
 76     }
 77 
 78     /**
 79      * 將map轉換成Javabean
 80      *
 81      * @param javabean javaBean
 82      * @param data     map數據
 83      */
 84     public static Object toJavaBean(Object javabean, Map<String, String> data) {
 85         Method[] methods = javabean.getClass().getDeclaredMethods();
 86         for (Method method : methods) {
 87             try {
 88                 if (method.getName().startsWith("set")) {
 89                     String field = method.getName(); //setName   setPassword
 90                     field = field.substring(field.indexOf("set") + 3);//Name  Password
 91                     field = field.toLowerCase().charAt(0) + field.substring(1);//name  password
 92                     method.invoke(javabean, new Object[]
 93                             {
 94                                     data.get(field)
 95                             });
 96                 }
 97             } catch (Exception e) {
 98                 e.printStackTrace();
 99             }
100         }
101 
102         return javabean;
103     }
104 
105     /**
106      * 將javaBean轉換成JSONObject
107      *
108      * @param data javaBean
109      * @return json對象
110      * @throws ParseException json解析異常
111      */
112     public static void toJavaBean(Object javabean, String data) throws ParseException {
113         JSONObject jsonObject = new JSONObject(data);
114         Map<String, String> datas = BeantoMap(jsonObject);
115         toJavaBean(javabean, datas);
116     }
117 }

 

方法調用:htm

 1 package com.suning.crawler.util;
 2 import net.sf.json.JSONObject;
 3 import org.junit.Test;
 4 
 5 import java.util.HashMap;
 6 import java.util.Map;
 7 import java.util.Set;
 8 
 9 /**
10  * @Author: hoobey
11  * @Description:
12  * @Date: Created in 9:16 2018/1/6
13  * @Modified By:
14  */
15 public class Test0106 {
16     /*javaBean轉換成Map*/
17     @Test
18     public void test1(){
19         Map<String, String> map = BeanConverter.BeantoMap(new Stu("hoobey","123"));
20        // Map<String, String> map = BeanConverter.toMap(new Stu("hoobey", "213"));
21       //  Set<Map.Entry<String, String>> entry = map.entrySet(); //Set集合中存儲的是Map.Entry<String, String> entry
22         //推薦使用這種map遍歷 尤爲是容量大的時候  map.entrySet()返回此映射中包含的映射關係的 Set視圖
23         for(Map.Entry<String, String> entry : map.entrySet()){
24             System.out.println("key="+entry.getKey()+",value="+entry.getValue());
25         }
26     }
27 
28     /*  * 將json對象轉換成Map*/
29     @Test
30     public void test2(){
31 
32         JSONObject json =new JSONObject();
33         json.put("hoobey","123");          //{"hoobey":"123"}
34         Map<String, String> toMap = BeanConverter.JsontoMap(json);
35         for(Map.Entry<String, String> entry : toMap.entrySet()){
36             System.out.println("key="+entry.getKey()+",value="+entry.getValue());
37         }
38     }
39 
40     /*將javaBean轉換成JSONObject*/
41     @Test
42     public void test3(){
43         JSONObject toJSON = BeanConverter.toJSON(new Stu("hoobey", "123"));
44         System.out.println(toJSON);//{"password":"123","name":"hoobey"}
45     }
46 
47     /*將map轉換成Javabean   map中存放的鍵值必定和bean相對應*/
48     @Test
49     public void test4(){
50         Map<String, String> map = new HashMap<String, String>();
51         map.put("name","hoobey");
52         map.put("password","123");
53         Object o = BeanConverter.toJavaBean(new Stu(), map);
54         System.out.println(o);//Stu{name='hoobey', password='123'}
55     }
56 }

這個寫的很詳細,轉載自:http://www.javashuo.com/article/p-aeekoyhs-cs.html對象

相關文章
相關標籤/搜索