0
我創建了一個方法「Json to HashTable」,反之亦然。我使用HashTable是因爲「Java」沒有關聯數組。現在我的問題是在json中有一個數組。這意味着從「Java」的HashTable數組:/根本不工作,但我認爲解決方案是使用「列表」任何幫助?這難道還是我複雜了嗎?Json/JsonArray到Android中的HashTable/List
Json的例子:
{"Config":[{"Name":"method1","Uses":"0","Event":["Start","Play"],"Action":{"Class":"Ads","Options":{"Class":"Webview","Url":"http:\/\/test.com\/action.php","Time":"10"}}},{"Name":"method2","Uses":"12","Event":["Loading"],"MaxTimes":"5","Options":{"Class":"Ads"}}]}
觀:http://json.parser.online.fr/
我的代碼:
public Hashtable<?, ?> JSonDecode(String data) {
Hashtable<String, Object> htJS = new Hashtable<String, Object>();
try {
JSONObject objJS = new JSONObject(data);
Iterator<String> it = objJS.keys();
String key = null;
Object value = null;
while (it.hasNext()) {
key = it.next();
value = objJS.get(key);
if (value instanceof JSONObject) {
value = JSonObjectToHashtable(value.toString());
}
if (value instanceof JSONArray) {
value = JSonArrayToHashtable(value.toString());
}
htJS.put((String) key, value);
}
} catch (JSONException e) {
e.printStackTrace();
// No valid json
return null;
}
return htJS;
}
public Hashtable<?, ?> JSonObjectToHashtable(String data) {
Hashtable<String, Object> htJS = new Hashtable<String, Object>();
JSONObject objJS;
try {
objJS = new JSONObject(data);
Iterator<String> it = objJS.keys();
String key = null;
Object value = null;
while (it.hasNext()) {
key = it.next();
value = objJS.get(key);
if (value instanceof JSONObject) {
value = JSonObjectToHashtable(value.toString());
}
htJS.put((String) key, value);
}
} catch (JSONException e) {
e.printStackTrace();
}
return htJS;
}
public List<Map<String, Object>> JSonArrayToHashtable(String data) {
List<Map<String, Object>> listMap = new ArrayList<Map<String,Object>>();
Map<String,Object> entry = new HashMap<String,Object>();
JSONArray objJSA;
try {
objJSA = new JSONArray(data);
for (int i = 0; i < objJSA.length(); i++) {
JSONObject objJS = objJSA.getJSONObject(i);
Iterator<String> it = objJS.keys();
String key = null;
Object value = null;
while (it.hasNext()) {
key = it.next();
value = objJS.get(key);
if (value instanceof JSONObject) {
value = JSonObjectToHashtable(value.toString());
}
entry.put((String) key, value);
}
listMap.add(entry);
entry = new HashMap<String,Object>();
}
} catch (JSONException e) {
e.printStackTrace();
}
return listMap;
}
感謝提到響應樹類型(數組,列表等)。那麼,使用包含所有格式的Json處理Android的最佳做法是直接使用JsonObject和JSONArray? – TyrionLannister
很難給出建議,因爲這一切都取決於應用程序。我的個人偏好是使用Cursors與內容提供者合作,通過Sync Adapters與緩存響應(JSON-> SQLite)與服務器通信,並使用ContentResolver.notifyChange(...)重新驗證UI,但涉及很多移動部分。 – Y2i