2013-04-05 135 views
-8

嗨,我正好卡在有線那種problem.May的是我無法用我的心權。JSON解析正確的解決方案

我越來越喜歡

{ 
"Result":[ 
    "Entertainment", 
    "Business", 
    "Sports", 
    "Technology"] 
} 

我能夠得到的第一個值I,E的結果值這樣 在後執行環路響應JSON響應被

["Entertainment","Business","Sports","Technology"] 

現在問題是我得到的響應不像數組那樣是字符串。那麼我怎樣才能分別獲取這些值。 請幫助儘快

回答

0

這樣的(和jsonString是從服務器源JSON響應):

JSONObject json = new JSONObject(jsonString); 
JSONArray resultArray = json.getJSONArray("Result"); 

,然後簡單地遍歷resultArrayget()

2

問題是,我收到響應作爲字符串不是作爲陣列

=>如你SA ID您有響應爲字符串,那麼你只需要使用你所得到的響應字符串從它使用下面創建的JSONObject,然後取JSONArray:

try{ 
    JSONObject objJSON = new JSONObject(objResponse); 
    JSONArray arrayResponse = objJSON.getJSONArray("Result"); 

    // iterate through the JSONArray and fetch one by one string 
} catch (JSONException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 
+0

@Vyas瞭解JSON解析[這裏](http://www.technotalkative.com/android-json-parsing/)。 – 2013-04-05 10:43:44

0

您可以獲取Results陣列的每個String值,從JSON字符串是這樣的: -

JSONObject jsonObj = new JSONObject(jsonString); 
JSONArray resultArray = jsonObj.getJSONArray("Result"); 
for(int i=0;i<resultArray.length();i++){ 
    System.out.println(resultArray.getString(i)); // Get each String. 
} 
0

您可以分析您的JSON這樣

try { 
     JSONObject obj=new JSONObject(""); 
     JSONArray arr=obj.getJSONArray("Result"); 
    } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
0

嘗試像

JSONObject jsonObj = new JSONObject(json); 
JSONArray resultArray = jsonObj.getJSONArray("Result"); 

for(int i=0;i<resultArray.length();i++){ 

    JSONObject jsonObj = resultArray.getJSONObject(i); 
    String Entertainment= jObject.getString("Entertainment"); 
    String Business= jObject.getString("Business"); 
    String Sports = jObject.getString("Sports"); 
    String Technology = jObject.getString("Technology "); 

} 
0

解析您的JSONArray並返回一個字符串ArrayList,試試這個:

JSONObject json = new JSONObject(jsonString); 
    JSONArray jsonArray = jsonObj.getJSONArray("Result"); 
    if(jsonArray!= null) { 
     ArrayList<String> arrayResult = new ArrayList<String>(); 
     for(int i=0;i<jsonArray.length();i++){ 
      arrayResult.add(arrayResult.getString(i)); 
     } 
    } 

注意:你應該把這個try catch集團趕上JSONException

0

我有解決了這個問題

JSONParser jParser = new JSONParser(); 
    // getting JSON string from URL 
    JSONObject json = jParser.getJSONObjectFromUrl(url); 
    Log.e("json is", "--------------"+json); 
    programResponse = json.getString("Result"); 
    Log.e("in the post-execute loop", "in the post-execute loop response is"+programResponse); 
    JSONArray arrayResponse = new JSONArray(programResponse); 
    for(int i = 0; i < arrayResponse.length(); i++){ 
    //JSONArray innerJsonArray = json.getJSONArray(i); 
    String jsonObject = arrayResponse.getString(i); 
    System.out.println(jsonObject); 
    Log.e("length is", "--------------"+jsonObject); 
    programValues.add(jsonObject); 
}