【问题标题】:Parse json tag inside another tag在另一个标签内解析 json 标签
【发布时间】:2019-06-28 16:35:25
【问题描述】:

我在解析另一个标签内的标签时遇到问题。 我有一个结构如下的 json 文件:

 "articles":[
             {
             "source":
                     {
                     "id":"generic-news",
                     "name":"Generic News"
                     },
             "author":" author's name",
             "title":"your title",
             "url":" your url",
             "publishedAt":"date",
             "content":"your content"
             },

我在解析源、作者、标题、url、publishAt 和内容时没有问题,但我无法获取 id 和命名它只会给我一个错误。 这是我的代码:

JSONObject jsonObject = new JSONObject(result);
            //result is the entire json file
            String newsInfo = jsonObject.getString("articles");

            JSONArray arr = new JSONArray(newsInfo);


            for(int i= 0; i < arr.length();i++){
                JSONObject jsonPart = arr.getJSONObject(i);

                Log.i("source", jsonPart.getString("source"));
                temp = jsonPart.getString("source");
                textView.append(temp+ "\n");
                Log.i("author", jsonPart.getString("author"));
                Log.i("title", jsonPart.getString("title"));
                temp = jsonPart.getString("title");
                textView.append(temp+ "\n");
                Log.i("description", jsonPart.getString("description"));
                temp = jsonPart.getString("description");
                textView.append(temp+ "\n");
                Log.i("url", jsonPart.getString("url"));
                temp = jsonPart.getString("url");
                textView.append(temp+ "\n");
                Log.i("publishedAt", jsonPart.getString("publishedAt"));
                temp = jsonPart.getString("publishedAt");
                textView.append(temp+ "\n");
                Log.i("content", jsonPart.getString("content"));
                temp = jsonPart.getString("content");
                textView.append(temp+ "\n");
        }

我的应用正确地打印了作者姓名、标题、网址、日期和内容,但使用源它打印 {"id" : "generic-news", "name":"Generic News"}。 我尝试使用与文章相同的方法,但没有成功。

【问题讨论】:

    标签: java android json


    【解决方案1】:

    "source" 不是字符串,而是 Json 对象。所以你需要这样做:

    JsonObject obj = jsonPart.getJSONObject("source");
    String name = obj.getString("name");
    String id = obj.getString("id");
    

    【讨论】:

      猜你喜欢
      • 2013-04-17
      • 2016-09-20
      • 2020-03-04
      • 1970-01-01
      • 1970-01-01
      • 2016-01-17
      • 2021-09-29
      • 2014-10-04
      • 1970-01-01
      相关资源
      最近更新 更多