2013-07-15 32 views
1

因此,我正在處理來自JSON對象的返回值,並試圖返回其中一個鍵的值。所以我得到的JSON對象就是這個。如何訪問從JSON對象返回的值

{"options":[{"picture":"http:\/\/example.com\/1.png", contact_id="1", name="Tom"}, {"picture":"http:\/\/example.com\/2.png", contact_id="2", name="Jess"}]} 

現在我處理它的Android應用程序,當我有一個叫做最後的靜態字符串說,這是設置爲選項

private static final String TAG = "options"; 

TAG,我用它來記錄這樣的JSON值

Log.d("Friends name", jsn.getString(TAG)); 

我得到的第一個結果

{"options":[{"picture":"http:\/\/example.com\/1.png", contact_id="1", name="Tom"},  {"picture":"http:\/\/example.com\/2.png", contact_id="2", name="Jess"}]} 

但是我試圖只訪問這些名字,但我並不知道如何去做。

我試着設置TAG來options[0].name得到公正的第一個名字,但它給了我一個錯誤

JSONException:沒有價值選項[0]。名稱

我有點迷失在這裏。

+1

首先檢查http://jsonlint.com/我檢查你所提供的JSON你的JSON輸出,它有一個錯誤.. – Krrishnaaaa

+1

我認爲應該是「:」而不是「=」。 –

+0

使用'jsn.options [0] .name訪問名字''在你的情況下''TAG = jsn.options [0] .name;'。 – g00dy

回答

3

如果你在談論JSON,那麼你已經發布的字符串不是有效的JSON。

它應該如下。

{ 
    "options": [ 
     { 
      "picture": "http://example.com/1.png", 
      "contact_id": "1", 
      "name": "Tom" 
     }, 
     { 
      "picture": "http://example.com/2.png", 
      "contact_id": "2", 
      "name": "Jess" 
     } 
    ] 
} 

然後寫下面的代碼片段來獲取名稱。

JSONObject android = new JSONObject(json_string); 

JSONArray array = android.getJSONArray("options"); 

for (int i = 0; i < array.length(); i++) { 
    Log.i("name", array.getJSONObject(i).getString("name")); 
} 
+0

完美。謝啦。這工作。 –

0

您需要創建JSONArray並獲得價值

JSONArray jsonArr = jsn.getJSONArray(TAG); 
String name=jsonArr.get(0).getString("name"); 
0
JSONObject object=new JSONObject(Your String...); 
JsonArray jArray=object.getJsonArray("options"); 
for(int i=0;i<jArray.length;i++) 
{ 
    JSONObject jObject=jArray.getJSONObject(0); 
String picture=jObject.getString("picture"); 
int id=JObject.getInt("contact_id"); 
    String name=JObject.getString("name"); 

}