【问题标题】:Java JSON pulling value from selected name in JSONObject from JSONArrayJava JSON 从 JSONArray 中的 JSONObject 中的选定名称中提取值
【发布时间】:2011-04-28 05:44:28
【问题描述】:

我正在尝试从从 JSONArray 创建的 JSONbject 中的名称中提取值,JSONAarray 是从 main(root) 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"));

感谢您的浏览,非常感谢您提供任何答案。

【问题讨论】:

  • 你想从上面的 json 对象中获取文件名?
  • 对不起,我输入了错误的代码。我会更新的。

标签: java android json


【解决方案1】:

您可能希望简化 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();
}

【讨论】:

  • 我明白你简化 JSON 的意思,但将来 JSON 中会列出更多文件。我打算使用“for”循环来解析它们。再次感谢朋友,非常感谢您的帮助。
  • @SpicyKarl 当然,这就是数组的原因。我只是说你不需要编号标签,例如{"array":[{"item1"}{"item2"}{"item3"}]}
  • 好的,现在我明白你的意思了。我将按照您的建议简化 JSON,这将帮助我解析 JSONArray 中的多个条目。谢谢你所做的一切。
【解决方案2】:

对于获取单个值,您可以使用 JSONTokener:

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

【讨论】:

    【解决方案3】:

    【讨论】:

    • 谢谢,但我想在没有 gson 的情况下执行此操作。我已将 gson 添加到我的资源中并一直在查看示例,但没有找到更简单的方法来执行此操作而不使用 gson。
    • 你解析 json 是相当复杂的,但是在 Gson 的帮助下很容易亲爱的
    【解决方案4】:

    例如从上面的 json 字符串中检索文件名

    尝试 { 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); 字符串文件名 = jobj.getJSONObject("1").getString("文件名"); Toast.makeText(this, filename, Toast.LENGTH_SHORT).show(); } 捕捉(JSONException e){ e.printStackTrace(); }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多