2011-04-28 38 views
1

我想從JSONArray中創建的JSONbject中的名稱中提取值,JSONAarray是從主(根)JSONObject創建的。Java JSON從JSONArray中從JSONObject中選定的名稱中提取值

這裏的JSON:

{"filelist": [{ 
"1": { 
    "filename": "sample.mp3", 
    "baseurl": "http://etc.com/" 
}}]} 

我相當肯定的JSON格式正確無誤。

這裏是Java(Android的SDK,這是在主Activity類的onCreate方法):

String jsonString = new String("{\"filelist\": [{ \"1\": { \"filename\": \"sample.mp3\", \"baseurl\": \"http://etc.com/\" }}]}"); 
JSONObject jObj = new JSONObject(jsonString); 
JSONArray jArr = new JSONArray(jObj.getJSONArray("filelist").toString()); 
JSONObject jSubObj = new JSONObject(jArr.getJSONObject(0).toString()); 
textView1.setText(jSubObj.getString("filename")); 

感謝您抽空看一看,任何答案都非常讚賞。

+0

你想從上面的json對象中檢索文件名? – sat 2011-04-28 05:48:31

+0

你的問題是什麼? – MByD 2011-04-28 05:49:12

+0

對不起,我輸入了錯誤的代碼。我會更新它。 – SpicyKarl 2011-04-28 05:54:00

回答

4

你可能會想簡化JSON結構,但是你可以按照如下現在閱讀:

JSONObject jObj; 
try { 
    jObj = new JSONObject(jsonString); 
    JSONArray jArr = jObj.getJSONArray("filelist"); 
    JSONObject jObj2 = jArr.getJSONObject(0); 
    textView1.setText(jObj2.getJSONObject("1").getString("filename")); 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 

如果你將有連續的號碼JSON數組,那麼你可以考慮取消這些:

{"filelist": [ 
    { 
    "filename": "sample.mp3", 
    "baseurl": "http://etc.com/" 
    } 
]} 

需要少了一個步驟:

JSONObject jObj; 
try { 
    jObj = new JSONObject(jsonString); 
    JSONArray jArr = jObj.getJSONArray("filelist"); 
    JSONObject jObj2 = jArr.getJSONObject(0); 
    textView1.setText(jObj2.getString("filename")); 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 
+0

非常感謝!這工作完美。 – SpicyKarl 2011-04-28 06:09:18

+0

我明白你的意思是簡化JSON,但將來會有更多的文件在JSON中列出。我打算使用「for」循環來解析它們。再次感謝朋友,我非常感謝你的幫助。 – SpicyKarl 2011-04-28 06:21:07

+0

@SpicyKarl當然,這就是爲什麼是一個數組。我只是說你不需要編號標籤,例如'{「array」:[{「item1」} {「item2」} {「item3」}]}' – Aleadam 2011-04-28 06:25:51

1
+0

謝謝,但我想這樣做沒有gson。我已經將gson添加到了我的資源中,並且一直在尋找示例,但是沒有找到更簡單的方法來在沒有gson的情況下執行此操作。 – SpicyKarl 2011-04-28 06:00:52

+0

你解析json是相當複雜的,但在Gson的幫助下它非常容易親愛的 – 2011-04-28 06:03:31

2

爲了獲取單值可以使用JSONTokener:

JSONObject object = (JSONObject) new JSONTokener("JSON String").nextValue();
String lstatus=object.getString("filename");

0

例如從上面檢索文件名json字符串

 
try { 
      String jsonString = new String("{\"filelist\": [{ \"1\": { \"filename\": \"sample.mp3\", \"baseurl\": \"http://www.hostchick.com/deemster/\" }}]}"); 
      JSONObject jObj = new JSONObject(jsonString); 
      JSONArray jArr; 
      jArr = jObj.getJSONArray("filelist"); 
      JSONObject jobj = jArr.getJSONObject(0); 
      String filename = jobj.getJSONObject("1").getString("filename"); 
      Toast.makeText(this, filename, Toast.LENGTH_SHORT).show(); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

+0

謝謝你。你的代碼也可以工作。 :) – SpicyKarl 2011-04-28 06:16:17