2011-04-28 40 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