【问题标题】:android - parsing JSONArray that doesn't have explicit JSONObjectandroid - 解析没有显式 JSONObject 的 JSONArray
【发布时间】:2015-07-11 09:47:58
【问题描述】:

我知道如何解析类似于 [{...},{...},{...}] 的 JSON。但这是我的例子,有些不同:

[{"type":"sometype","presentations":["/files/presentation/presentation.pdf"],"description":"somedescription"},{"type":"sometype","presentations":["/files/presentation/presentation2.pdf"],"description":"somedescription"}]

如何在此处解析“演示文稿”中的数据?我将它作为 JSONArray 获取,但无法获取值(使用 .toString() 与该数组返回该值,但在“/”之前使用“\”(我的意思是“/files/presentation...”) ,所以我无法将它添加到 url 以显示 pdf。而且我不知道如何从该数组中获取 JSONObject(当然,如果它存在的话)。

【问题讨论】:

  • 你已经试过了,你能把代码贴在你正在解析的地方吗?
  • 我可以照原样复制粘贴它,但稍后。用自然语言说,我将此字符串转换为 JSONArray,然后通过其编号从该数组中提取 JSONObject,然后执行 .getString("presentations"),然后将其转换为 JSONArray(因为它应该是数组,对吗?)。此外,我做了几件事:1)我认为它是一个隐式 JSONObject,所以我尝试通过数字 0 获取 jSONObject,然后将其转换为字符串,但我记得我什至无法获取 Object。 2)我试图转换为字符串JSONArray本身希望在没有[]的情况下对其进行子串化,结果(“\/”)如上所述
  • 首先你可以检查来自服务器的响应的json有几个站点First linkSecond link。您可以在这里检查您的json是否正确,您可以清楚地看到哪个是普通字段或对象或数组。
  • @JustinMcGuire 我的回答对你有用吗?
  • @AlexandreG 完成。我想投赞成票,但到目前为止我的评分并没有让我满意。唯一的——请改成“string2”中的getJSONObject(1),可能有些初学者不会一下子搞定,为什么string和string2是一样的:)

标签: android arrays json parsing


【解决方案1】:
String jsonString = "[{\"type\":\"sometype\",\"presentations\":[\"/files/presentation/presentation.pdf\"],\"description\":\"somedescription\"},{\"type\":\"sometype\",\"presentations\":[\"/files/presentation/presentation2.pdf\"],\"description\":\"somedescription\"}]";

try {
    JSONArray jaArray = new JSONArray(jsonString);
    JSONObject firstElement = jaArray.getJSONObject(0);
    JSONArray jaPresentations = firstElement.getJSONArray("presentations");
    String string = jaPresentations.getString(0);

    //or chain it together like so:
    String string2 = jaArray.getJSONObject(1).getJSONArray("presentations").getString(0);

    Log.v("TAG", string);
    Log.v("TAG", string2);

输出:

V/TAG﹕ /files/presentation/presentation.pdf
V/TAG﹕ /files/presentation/presentation2.pdf

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多