本文介绍了Java的JSON从选定的名称中的JSONObject从JSONArray拉动价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拉一个从J​​SONArray创建JSONbject从名称的值,则JSONAarray从主(根)创建的JSONObject。

I'm trying to pull a value from a name in a JSONbject that is created from a JSONArray, the JSONAarray is created from the main(root) JSONObject.

这里的JSON:

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

我相当肯定的JSON格式正确无误。

I'm fairly sure the JSON is correctly formatted.

下面是Java(Android的SDK,这是在主Activity类的onCreate方法):

Here is the Java (for Android SDK, this is in the OnCreate method in main Activity class):

    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"));

感谢您抽空看看,任何答案是多少AP preciated。

Thanks for taking a look and any answers are much appreciated.

推荐答案

您可能会想简化JSON结构,但是可以如下现在阅读:

You will probably want to simplify the JSON structure, but you can read it now as follows:

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数组中有连续的号码,那么你可以考虑消除它们:

If you are going to have consecutive numbers in the JSON array, then you might consider eliminating them:

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

将要求少了一个步骤:

Would require one less step:

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();
}

这篇关于Java的JSON从选定的名称中的JSONObject从JSONArray拉动价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 02:00