Android JSON 嵌套数组

标签 android json

我试图在这类问题中模仿选择的答案,但我不确定为什么我无法检索其中“附件”的 URL。

我所追求的是获取每个“帖子”然后获取每个“附件”图像 URL 以保存为字符串的方法。我试过在我的模拟器上这样做,但它只是停止并永远运行。由于某些原因,我也无法将我的真实手机用作调试器,否则我会发布一个 logcat。

我可以肯定的是,除附件外,所有内容都正确进入。我设法下载了帖子,但无法下载任何嵌套的内容。我是 JSON 的新手,所以非常感谢任何帮助。

我的异步:

 // you can make this class as another java file so it will be separated from your main activity.
        // https://www.codeofaninja.com/2013/11/android-json-parsing-tutorial.html
        public class AsyncTaskParseJson extends AsyncTask<String, String, String> {

            private ArrayList<RssFeedItem> tempArray = new ArrayList<RssFeedItem>();
            final String TAG = "AsyncTaskParseJson";
            private ProgressDialog progress;

            // set your json string url here
            String yourJsonStringUrl = "http://www.prindlepost.org/?json=tag_slug=java";

            // contacts JSONArray
            JSONArray dataJsonArr = null;
            JSONArray imageURLArr = null;

            @Override
            protected void onPreExecute() {
                progress = new ProgressDialog(getActivity());
                progress.setTitle("Downloading Prindle's Posts");
                progress.setMessage("This should just take a moment.");
                progress.show();
            }

            @Override
            protected String doInBackground(String... arg0)
            {
                try
                {
                    // instantiate our json parser
                    JsonParser jParser = new JsonParser();

                    // get json string from url
                    JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);

                    // get the array of users
                    dataJsonArr = json.getJSONArray("posts");

                    // loop through all users
                    for (int i = 0; i < dataJsonArr.length(); i++)
                    {
                        JSONObject c = dataJsonArr.getJSONObject(i);
                        // Storing each json item in variable
                        String id = c.getString("id");
                        String type = c.getString("type");
                        String slug = c.getString("slug");
                        String title = c.getString("title");
                        String content = c.getString("content");
                        String author = c.getString("author");

                        //http://stackoverflow.com/questions/19748829/android-get-json-array-nested-in-array
                        JSONObject attachments = c.getJSONObject("attachments");

                        Log.d("attachment",""+attachments.getString("url"));


                        // show the values in our logcat
                        Log.e(TAG, "id: " + id
                                + ", type: " + type
                                + ", slug: " + slug
                                + ", title: " + title
                                + ", author: " + author
                                + ", content: " + content + "\n\n");

                        tempArray.add(new RssFeedItem(title, content, "", 0, new Date(), author));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return null;
            }

JSON:http://www.pridlepost.org/?json=tag_slug=java

{
status: "ok",
count: 10,
count_total: 334,
pages: 34,
posts: [
{
id: 4230,
type: "post",
slug: "crowdsourcing-justice",
url: "http://www.prindlepost.org/2015/06/crowdsourcing-justice/",
status: "publish",
title: "Crowdsourcing Justice",
title_plain: "Crowdsourcing Justice",
content: "<p>The video begins abruptly. Likely recorded on a phone, the footage is shaky and blurry, yet the subject is sickeningly unmistakeable: a crying infant being repeatedly and violently dunked into a bucket of water. First it is held by the arms, then upside down by one leg, then grasped by the face as an unidentified woman pulls it through the water. Near the end of the video, the infant falls silent, the only remaining audio the splashing of water and murmured conversation as the child is dunked again and again.</p> <div class="more-link-wrap wpb_button"> <a href="http://www.prindlepost.org/2015/06/crowdsourcing-justice/" class="more-link">Read more</a></div> ",
excerpt: "<p>Facebook&#8217;s decision not to censor a video of child abuse poses questions of censorship, activism and online justice. </p> ",
date: "2015-06-09 14:00:19",
modified: "2015-06-10 09:53:36",
categories: [
{
id: 433,
slug: "crime-and-law",
title: "Crime and Law",
description: "",
parent: 63,
post_count: 14
},
{
id: 38,
slug: "ethics-news",
title: "Ethics News",
description: "",
parent: 0,
post_count: 153
},
{
id: 63,
slug: "society-ethics-news",
title: "Society",
description: "",
parent: 38,
post_count: 187
}
],
tags: [
{
id: 180,
slug: "abuse",
title: "abuse",
description: "",
post_count: 2
},
{
id: 481,
slug: "child-abuse",
title: "child abuse",
description: "",
post_count: 1
},
{
id: 482,
slug: "doxxing",
title: "doxxing",
description: "",
post_count: 1
},
{
id: 57,
slug: "facebook",
title: "Facebook",
description: "",
post_count: 4
},
{
id: 470,
slug: "internet",
title: "internet",
description: "",
post_count: 2
},
{
id: 130,
slug: "justice",
title: "justice",
description: "",
post_count: 2
},
{
id: 59,
slug: "social-media",
title: "social media",
description: "",
post_count: 4
}
],
author: {
id: 43,
slug: "connergordon_2016",
name: "Conner Gordon",
first_name: "Conner",
last_name: "Gordon",
nickname: "connergordon_2016",
url: "http://connergordon.tumblr.com",
description: "Conner is a web and social media intern at the Prindle Institute. A Political Science and English double major from Carmel, Indiana, Conner's ethical interests lie in memory studies, conflict analysis and the ethics of representation. He also has interests in literature, art and photography."
},
comments: [ ],
attachments: [
{
id: 4233,
url: "http://www.prindlepost.org/wp-content/uploads/2015/06/Screen-Shot-2015-06-09-at-11.48.59-AM.png",
slug: "screen-shot-2015-06-09-at-11-48-59-am",
title: "",
description: "",
caption: "Image credit: Screenshot from Youtube",
parent: 4230,
mime_type: "image/png",
images: [ ]
},
{
id: 4235,
url: "http://www.prindlepost.org/wp-content/uploads/2015/06/Screen-Shot-2015-06-09-at-11.48.59-AM1.png",
slug: "screen-shot-2015-06-09-at-11-48-59-am-2",
title: "",
description: "",
caption: "<a href="https://www.youtube.com/watch?v=UOCB8j6QgeI&bpctr=1433876092">Image/Youtube</a>",
parent: 4230,
mime_type: "image/png",
images: [ ]
}
],

最佳答案

我遇到了同样的问题。几天后我的大脑融化了,我尝试使用谷歌的 GSON。它为您完成所有的解析和思考,并返回一个漂亮的小对象,其中包含来自 JSON 的所有信息。

这是项目链接:https://github.com/google/gson

要使用它,您必须像这样实例化一个新的Gson 解析器

Gson gson = new Gson();
YourObject object = gson.fromJson(jsonString, YourObject.class);

YourObject 类应该如下所示:

public class YourObject{
    int status;
    int count;
    String count_total;
    ...
    Post[] posts;
}

现在您使用 JSON 中预测的字段创建一个 Post 类:

public class Post{
    int id;
    String type;
    String slug;
    ...
    Category[] categories;
}

我认为您可以了解如何设置 POJO。请记住,如果您在 JSON 中获取对象数组作为基础对象,请务必在调用 gson 时使用 YourObject[] 而不是 YourObject .fromJson

请注意:如果任何 Json 元素具有 null 或空值,即使它们主要是 YourObject 中的 int 类,最好将它们声明为String以避免java.lang.NumberFormatException

关于Android JSON 嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30765056/

相关文章:

android - MVP和Android处理Lifecycle事件,UI逻辑在哪里做

android - Android Studio 中的选项卡式 Activity 模板不适用于 Lollipop

javascript - ajax 请求中 json key 未正确发送

java - Android Studio > GridLayout > 如何获取单元格的位置?

android - 在两个 Activity 之间传递 bool Intent

jquery - .getJSON() 返回 null

java - 将Json反序列化为java对象

json - Power BI 和 JSON 数据

javascript - Angular2 等待 JSON 文件加载

android - 将数据从 Android 发送到 Webservice 以插入到我的数据库中