Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 資訊

Android 中 JSON 字符串與 JSON 對象的轉換

編輯:Android 資訊

這是一個萬能的 JSON 字符串轉 JSON 對象轉換器(Java 實現),隻有百來行代碼,非常輕量小巧。它在一般場景下資源消耗極低、速度也夠快,尤其適合 Android 應用開發。

通過 CommonJSONParser,可以把 JSON 字符串轉成由 Map、List、String、Integer 等標准 Java 對象組成的集合,用法如下:

CommonJSONParser commonJSONParser = new CommonJSONParser(); Map<String, Object> result = commonJSONParser.parse(jsonDataStr);

CommonJSONParser 源碼如下(核心思想是"遞歸"):

1 import java.util.ArrayList; 2 import java.util.HashMap; 3 import java.util.Iterator; 4 import java.util.List; 5 import java.util.Map; 6 7 import org.json.JSONArray; 8 import org.json.JSONException; 9 import org.json.JSONObject; 10 11 public class CommonJSONParser { 12 13 public Map<String, Object> parse(String jsonStr) { 14 15 Map<String, Object> result = null; 16 17 if (null != jsonStr) { 18 try { 19 20 JSONObject jsonObject = new JSONObject(jsonStr); 21 result = parseJSONObject(jsonObject); 22 23 } catch (JSONException e) { 24 // TODO Auto-generated catch block 25 e.printStackTrace(); 26 } 27 } // if (null != jsonStr) 28 29 return result; 30 } 31 32 private Object parseValue(Object inputObject) throws JSONException { 33 Object outputObject = null; 34 35 if (null != inputObject) { 36 if (inputObject instanceof JSONArray) { 37 outputObject = parseJSONArray((JSONArray) inputObject); 38 } else if (inputObject instanceof JSONObject) { 39 outputObject = parseJSONObject((JSONObject) inputObject); 40 } else if (inputObject instanceof String || inputObject instanceof Boolean || inputObject instanceof Integer) { 41 outputObject = inputObject; 42 } 43 44 } 45 46 return outputObject; 47 } 48 49 private List<Object> parseJSONArray(JSONArray jsonArray) throws JSONException { 50 List<Object> valueList = null; 51 52 if (null != jsonArray) { 53 valueList = new ArrayList<Object>(); 54 55 for (int i = 0; i < jsonArray.length(); i++) { 56 Object itemObject = jsonArray.get(i); 57 if (null != itemObject) { 58 valueList.add(parseValue(itemObject)); 59 } 60 } // for (int i = 0; i < jsonArray.length(); i++) 61 } // if (null != valueStr) 62 63 return valueList; 64 } 65 66 private Map<String, Object> parseJSONObject(JSONObject jsonObject) throws JSONException { 67 Map<String, Object> valueObject = null; 68 if (null != jsonObject) { 69 valueObject = new HashMap<String, Object>(); 70 71 Iterator<String> keyIter = jsonObject.keys(); 72 while (keyIter.hasNext()) { 73 String keyStr = keyIter.next(); 74 Object itemObject = jsonObject.opt(keyStr); 75 if (null != itemObject) { 76 valueObject.put(keyStr, parseValue(itemObject)); 77 } // if (null != itemValueStr) 78 } // while (keyIter.hasNext()) 79 } // if (null != valueStr) 80 81 return valueObject; 82 } 83 }

整體思路是:parseJSONObject 遍歷鍵值並遞歸調用 parseValue,parseValue 再根據元素類型分派給 parseJSONArray 或 parseJSONObject,從而實現任意嵌套結構的解析。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved