json格式解析的全過程

  1. package com.zml.pojo;  
  2.   
  3. /** 
  4.  * @author 鄭明亮 
  5.  * @Time:2016年2月2日 下午10:35:05 
  6.  * @version 1.0 
  7.  */  
  8. public class Person {  
  9.   
  10.     String name;  
  11.     String sex;  
  12.     String QQ;  
  13.     String contact;  
  14.   
  15.     public Person() {  
  16.         // TODO Auto-generated constructor stub  
  17.     }  
  18.   
  19.     public Person(String name, String sex, String qQ, String contact) {  
  20.         super();  
  21.         this.name = name;  
  22.         this.sex = sex;  
  23.         QQ = qQ;  
  24.         this.contact = contact;  
  25.     }  
  26.   
  27.     /** 
  28.      * @return the name 
  29.      */  
  30.     public String getName() {  
  31.         return name;  
  32.     }  
  33.   
  34.     /** 
  35.      * @param name 
  36.      *            the name to set 
  37.      */  
  38.     public void setName(String name) {  
  39.         this.name = name;  
  40.     }  
  41.   
  42.     /** 
  43.      * @return the sex 
  44.      */  
  45.     public String getSex() {  
  46.         return sex;  
  47.     }  
  48.   
  49.     /** 
  50.      * @param sex 
  51.      *            the sex to set 
  52.      */  
  53.     public void setSex(String sex) {  
  54.         this.sex = sex;  
  55.     }  
  56.   
  57.     /** 
  58.      * @return the qQ 
  59.      */  
  60.     public String getQQ() {  
  61.         return QQ;  
  62.     }  
  63.   
  64.     /** 
  65.      * @param qQ 
  66.      *            the qQ to set 
  67.      */  
  68.     public void setQQ(String qQ) {  
  69.         QQ = qQ;  
  70.     }  
  71.   
  72.     /** 
  73.      * @return the contact 
  74.      */  
  75.     public String getContact() {  
  76.         return contact;  
  77.     }  
  78.   
  79.     /** 
  80.      * @param contact 
  81.      *            the contact to set 
  82.      */  
  83.     public void setContact(String contact) {  
  84.         this.contact = contact;  
  85.     }  
  86.   
  87.     /* 
  88.      * (non-Javadoc) 
  89.      *  
  90.      * @see java.lang.Object#toString() 
  91.      */  
  92.     @Override  
  93.     public String toString() {  
  94.         return "Person [name=" + name + ", sex=" + sex + ", QQ=" + QQ  
  95.                 + ", contact=" + contact + "]";  
  96.     }  
  97.   
  98. }  


 

2.我寫了一個工具類,用來生成上述的四種類型的數據;

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. package com.zml.utils;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8. import com.zml.pojo.Person;  
  9.   
  10. /** 
  11.  * 用於生成四種類型的數據來測試json解析: 
  12.  * ①Person對象類型 ②List<Person> ③List<String> ④List<Map<String,Object>> 
  13.  *  
  14.  * @author 鄭明亮 
  15.  * @Time:2016年2月2日 下午10:38:40 
  16.  * @version 1.0 
  17.  */  
  18. public class DataUtil {  
  19.   
  20.     public static Person getPerson() {  
  21.   
  22.         return new Person("鄭明亮""男""1072307340""15733100573");  
  23.     }  
  24.   
  25.     public static List<Person> getPersons() {  
  26.         List<Person> list = new ArrayList<Person>();  
  27.         list.add(getPerson());  
  28.         list.add(new Person("張三""男""123456789""98765432"));  
  29.         list.add(new Person("李四""女""762348234""12312124324"));  
  30.         return list;  
  31.   
  32.     }  
  33.       
  34.     public static List<String>    getStrings(){  
  35.         List<String>list = new ArrayList<String>();  
  36.         list.add("鄭明亮");  
  37.         list.add("張三");  
  38.         list.add("李四");  
  39.           
  40.         return list;  
  41.     }  
  42.       
  43.     public static List<Map<String,Object>> getMaps(){  
  44.           
  45.         List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();  
  46.         Map<String,Object> map = new HashMap<String, Object>();  
  47.         map.put("name","鄭明亮" );  
  48.         map.put("blog""blog.csdn.net/zml_2015");  
  49.         map.put("person", getPerson());  
  50.         list.add(map);  
  51.         return list;  
  52.           
  53.     }  
  54.   
  55. }  


3.接下來就是寫json數據類型的轉換類了

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. package com.zml.utils;  
  2.   
  3. import net.sf.json.JSONObject;  
  4.   
  5. /** 
  6.  * @author 鄭明亮 
  7.  * @Time:2016年2月2日 上午12:18:38 
  8.  * @version 1.0 
  9.  */  
  10. public class JsonTools {  
  11.       
  12.       
  13.     public static String  createJsonString(String key,Object value){  
  14.           
  15.         JSONObject jsonObject=new JSONObject();  
  16.         jsonObject.put(key, value);  
  17.         return jsonObject.toString();  
  18.           
  19.         }  
  20.       
  21. }  


 

4.進行測試,看是否將上述4種數據轉換爲了json的數據類型

 

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. package com.zml.test;  
  2.   
  3. import com.zml.utils.DataUtil;  
  4. import com.zml.utils.JsonTools;  
  5.   
  6. /** 
  7.  * @author 鄭明亮 
  8.  * @Time:2016年2月2日 上午12:27:29 
  9.  * @version 1.0 
  10.  */  
  11. public class testjson {  
  12.   
  13.     public static void main(String[] args) {  
  14.             String jsonString;  
  15.             jsonString = JsonTools.createJsonString("person",DataUtil.getPerson());  
  16.   
  17.             System.out.println(jsonString);           
  18.             jsonString = JsonTools.createJsonString("persons",DataUtil.getPersons());  
  19.   
  20.             System.out.println(jsonString);           
  21.             jsonString = JsonTools.createJsonString("strings",DataUtil.getStrings());  
  22.   
  23.             System.out.println(jsonString);       
  24.             jsonString = JsonTools.createJsonString("maps",DataUtil.getMaps());  
  25.             System.out.println(jsonString);       
  26.         }  
  27.           
  28.       
  29.   
  30. }  


5.測試成功後,建立Servlet類,以方便將json數據傳輸給客戶端

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. <p>package com.zml.test;</p><p>import java.io.IOException;  
  2. import java.io.PrintWriter;</p><p>import javax.servlet.ServletException;  
  3. import javax.servlet.http.HttpServlet;  
  4. import javax.servlet.http.HttpServletRequest;  
  5. import javax.servlet.http.HttpServletResponse;</p><p>import com.zml.utils.DataUtil;  
  6. import com.zml.utils.JsonTools;</p><p>/** 
  7.  * @author 鄭明亮 
  8.  * @Time:2016年2月2日 下午10:54:26 
  9.  * @version 1.0 
  10.  */  
  11. public class JsonServlet extends HttpServlet {</p><p> /** 
  12.   * Constructor of the object. 
  13.   */  
  14.  public JsonServlet() {  
  15.   super();  
  16.  }</p><p> /** 
  17.   * Destruction of the servlet. <br> 
  18.   */  
  19.  public void destroy() {  
  20.   super.destroy(); // Just puts "destroy" string in log  
  21.   // Put your code here  
  22.  }</p><p> /** 
  23.   * The doGet method of the servlet. <br> 
  24.   *  
  25.   * This method is called when a form has its tag value method equals to get. 
  26.   *  
  27.   * @param request 
  28.   *            the request send by the client to the server 
  29.   * @param response 
  30.   *            the response send by the server to the client 
  31.   * @throws ServletException 
  32.   *             if an error occurred 
  33.   * @throws IOException 
  34.   *             if an error occurred 
  35.   */  
  36.  public void doGet(HttpServletRequest request, HttpServletResponse response)  
  37.    throws ServletException, IOException {  
  38.   this.doPost(request, response);</p><p> }</p><p> /** 
  39.   * The doPost method of the servlet. <br> 
  40.   *  
  41.   * This method is called when a form has its tag value method equals to 
  42.   * post. 
  43.   *  
  44.   * @param request 
  45.   *            the request send by the client to the server 
  46.   * @param response 
  47.   *            the response send by the server to the client 
  48.   * @throws ServletException 
  49.   *             if an error occurred 
  50.   * @throws IOException 
  51.   *             if an error occurred 
  52.   */  
  53.  public void doPost(HttpServletRequest request, HttpServletResponse response)  
  54.    throws ServletException, IOException {</p><p>  response.setContentType("text/html;charset=utf-8");  
  55.   request.setCharacterEncoding("utf-8");  
  56.   response.setCharacterEncoding("utf-8");  
  57.   PrintWriter out = response.getWriter();</p><p>  String jsonString="";  
  58.   String  actionString = request.getParameter("action");  
  59.     
  60.   if (actionString.equals("person")) {  
  61.      
  62.    jsonString = JsonTools.createJsonString("person",DataUtil.getPerson());</p><p>  } else if (actionString.equals("persons")) {  
  63.      
  64.    jsonString = JsonTools.createJsonString("persons",DataUtil.getPersons());</p><p>  } else if (actionString.equals("strings")) {  
  65.      
  66.    jsonString = JsonTools.createJsonString("strings",DataUtil.getStrings());</p><p>  } else if (actionString.equals("maps")) {  
  67.      
  68.    jsonString = JsonTools.createJsonString("maps",DataUtil.getMaps());  
  69.      
  70.   }  
  71.     
  72.   out.write(jsonString);</p><p> }</p><p> /** 
  73.   * Initialization of the servlet. <br> 
  74.   *  
  75.   * @throws ServletException 
  76.   *             if an error occurs 
  77.   */  
  78.  public void init() throws ServletException {  
  79.   // Put your code here  
  80.  }</p><p>}  
  81. </p>  


 通過網址訪問可得到的JSON數據:

二、客戶端解析json數據

這裏暫時只貼出重要的解析部分,

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. package com.zml.util;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.Iterator;  
  6. import java.util.List;  
  7. import java.util.Map;  
  8.   
  9. import org.json.JSONArray;  
  10. import org.json.JSONException;  
  11. import org.json.JSONObject;  
  12.   
  13. import com.zml.pojo.Person;  
  14.   
  15. /** 
  16.  * 解析數據:將json字符串解析還原成原來的數據類型 
  17.  *  
  18.  * @author 鄭明亮 
  19.  * @date 2016-2-3 上午12:11:57 
  20.  * @version 1.0 
  21.  */  
  22. public class JsonTools {  
  23.   
  24.     public static Person getPerson(String key, String jsonString) {  
  25.         Person person = new Person();  
  26.         // 將json字符串轉換成json對象  
  27.         try {  
  28.             JSONObject jsonObject = new JSONObject(jsonString);  
  29.             // 將json對象根據key(person),拿到對應的value(Person對象)值  
  30.             JSONObject jsonObject2 = jsonObject.getJSONObject(key);  
  31.             // 將拿到的對象set到一個person對象中  
  32.             person.setName(jsonObject2.getString("name"));  
  33.             person.setSex(jsonObject2.getString("sex"));  
  34.             person.setQQ(jsonObject2.getString("QQ"));  
  35.             person.setContact(jsonObject2.getString("contact"));  
  36.         } catch (JSONException e) {  
  37.             // TODO Auto-generated catch block  
  38.             e.printStackTrace();  
  39.         }  
  40.         return person;  
  41.   
  42.     }  
  43.   
  44.     public static List<Person> getPersons(String key, String jsonString) {  
  45.         List<Person> list = new ArrayList<Person>();  
  46.         JSONObject jsonObject;  
  47.         try {  
  48.             jsonObject = new JSONObject(jsonString);  
  49.             JSONArray Persons = jsonObject.getJSONArray(key);  
  50.             for (int i = 0; i < Persons.length(); i++) {  
  51.                 Person person = new Person();  
  52.                 JSONObject jsonObject2 = Persons.getJSONObject(i);  
  53.                 person.setName(jsonObject2.getString("name"));  
  54.                 person.setSex(jsonObject2.getString("sex"));  
  55.                 person.setQQ(jsonObject2.getString("QQ"));  
  56.                 person.setContact(jsonObject2.getString("contact"));  
  57.   
  58.                 list.add(person);  
  59.             }  
  60.         } catch (JSONException e) {  
  61.             // TODO Auto-generated catch block  
  62.             e.printStackTrace();  
  63.         }  
  64.   
  65.         return list;  
  66.     }  
  67.   
  68.     public static List<String> getStrings(String key, String jsonString) {  
  69.         List<String> list = new ArrayList<String>();  
  70.   
  71.         try {  
  72.             JSONObject jsonObject = new JSONObject(jsonString);  
  73.             JSONArray StringArray = jsonObject.getJSONArray(key);  
  74.             for (int i = 0; i < StringArray.length(); i++) {  
  75.                 String str = StringArray.getString(i);  
  76.                 list.add(str);  
  77.   
  78.             }  
  79.   
  80.         } catch (Exception e) {  
  81.             // TODO: handle exception  
  82.         }  
  83.   
  84.         return list;  
  85.   
  86.     }  
  87.   
  88.     public static List<Map<String, Object>> getMaps(String key,  
  89.             String jsonString) {  
  90.         List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();  
  91.   
  92.         try {  
  93.             JSONObject jsonObject = new JSONObject(jsonString);  
  94.             JSONArray mapsArray = jsonObject.getJSONArray(key);  
  95.             for (int i = 0; i < mapsArray.length(); i++) {  
  96.                 JSONObject jsonObject2 = mapsArray.getJSONObject(i);  
  97.                 Map<String, Object> map = new HashMap<String, Object>();  
  98.                 // 查看Map中的鍵值對的key值  
  99.                 Iterator<String> iterator = jsonObject2.keys();  
  100.   
  101.                 while (iterator.hasNext()) {  
  102.                     String json_key = iterator.next();  
  103.                     Object json_value = jsonObject2.get(json_key);  
  104.                     if(json_value==null){  
  105.                         //當鍵值對中的value爲空值時,將value置爲空字符串;  
  106.                         json_value="";  
  107.                     }  
  108.                     map.put(json_key, json_value);  
  109.                 }  
  110.                 list.add(map);  
  111.             }  
  112.         } catch (Exception e) {  
  113.             // TODO: handle exception  
  114.         }  
  115.         return list;  
  116.     }  
  117.   
  118. }  


需要注意的是上述,客戶端和服務器端雖然都用到了JSONObject類,但是引用的不是一個jar包中的內容哦;客戶端的是引用的 org.json.JSONObject;而服務器端引用的是net.sf.json.JSONObject;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章