2013-06-04 33 views
-1

我嘗試了很多,但是我無法解析這個在android中的JSON。在android中解析這個JSON

有人可以幫忙嗎?

[ 
    "m", 
    ["mapquest", "maps", "msn"], 
    ["", "", ""], 
    [], 
    { 
    "type": ["KEY", "KEY", "KEY"], 
    "PAIR": [1, 2, 3], 
    "COUNT": 3 
    } 
] 

這是我的代碼。

JSONArray result = new JSONArray(res); 

if (result.length() > 0){ 
for (int i = 0; i < result.length(); ++i) 
{ 
//it errors here.... 
JSONObject menuObject = result.getJSONObject(i); 
} 
} 
+2

有什麼錯誤? –

+1

這是JSON在任何時候的格式?或者你以前不知道哪一個是數組,哪一個不是? – Nezam

+2

這不是標準的JSON格式。 –

回答

3

嘗試解析當前JSON字符串爲:

JSONArray result = new JSONArray(res); 

if (result.length() > 0){ 
for (int i = 0; i < result.length(); ++i) 
{ 
    Object obj = result.get(i); 
    if (obj instanceof JSONArray) { 
    JsonArray jsonarr = (JSONArray)obj; 
    for (int j = 0; j < jsonarr.length();j++) 
     String str_one=jsonarr.optString(j); 
    } 
    }else{ 
     JSONObject jsonobj = (JSONObject)obj; 
     JsonArray jsonarr_type =jsonobj.getJSONArray("type"); 
     for (int j = 0; j < jsonarr_type.length();j++) 
     String str_typejsonarr_type.optString(j); 
     } 
     /// do same for PAIR 
    } 
} 
} 
+2

你應該包含一些關於代碼的細節,否則他/她從來不會在代碼中犯過什麼錯誤。 –

+0

真棒!!!!你救了我的一天! – jrebecca1

+0

實際上這個問題本身就是模糊的。從技術上講,'error'是定義問題的一個非常不明確的方法。除非你用'Logcat'轉儲支持它,或者讓我們瞭解拋出了什麼'Exception'。這是不可能的人們會猜測你的問題。 – Nezam

0

JSON包含數組和對象。您可以使用opt方法來檢查類型是什麼。如果optJSONObject返回Null,那麼它是一個數組。

JSONArray result = new JSONArray(res); 

if (result.length() > 0){ 
for (int i = 0; i < result.length(); ++i) 
{ 
    JSONObject menuObject = result.optJSONObject(i); 
    if(menuObject == null) 
    { 
     JSONArray arr = result.optJSONArray(i); 
     // process the array 
    } 
    else 
    { 
     // process the object 
    } 
}