添加JSONObject方法时,Android

时间:2016-04-25 15:03:35

标签: android json

我想开发一个网站的Android应用程序。我阅读了来自json的网站帖子,并在每{10}个帖子中显示RecyclerView
但我有奇怪的问题!在我的代码中添加此行时,jsonRecyclerView已限制并显示10个帖子的10个帖子实例!
代码:

JSONObject imagesPair=images.getJSONObject("martial-frontpage-blog");

当添加此行限制为5个帖子时,删除此行时没关系并显示10个帖子!
Json Link: Json link

AsyncTask代码:

public class MainDataInfo {
    private Context mContext;
    private String ServerAddress = ServerIP.getIP();

    public void getMainDataInfo(Context context) {
        mContext = context;
        new getInfo().execute(ServerAddress + "page=1");
    }

    private class getInfo extends AsyncTask<String, Void, String> {
        EventBus bus = EventBus.getDefault();
        private String ou_response;
        private List<MainDataModel> infoModels;

        @Override
        protected void onPreExecute() {
            CustomProcessDialog.createAndShow(mContext);
            infoModels = new ArrayList<>();
        }

        @Override
        protected String doInBackground(String... params) {
            OkHttpClient client = new OkHttpClient();

            Request request = new Request.Builder()
                    .url(ServerAddress + "page=1")
                    .build();

            Response response;
            try {
                response = client.newCall(request).execute();
                ou_response = response.body().string();
                response.body().close();
                if (ou_response != null) {
                    try {
                        JSONObject postObj = new JSONObject(ou_response);
                        JSONArray postsArray = postObj.getJSONArray("posts");
                        infoModels = new ArrayList<>();

                        for (int i = 0; i <= infoModels.size(); i++) {
                            JSONObject postObject = (JSONObject) postsArray.get(i);
                            int id = postObject.getInt("id");
                            String title = postObject.getString("title");
                            Log.d("Data", "Post id: " + id);
                            Log.d("Data", "Post title: " + title);

                            JSONObject images=postObject.getJSONObject("thumbnail_images");
                            JSONObject imagesPair=images.getJSONObject("martial-frontpage-blog");

                            //Use the title and id as per your requirement
                            infoModels.add(new MainDataModel(
                                    postObject.getInt("id"),
                                    postObject.getString("title"),
                                    postObject.getString("content"),
                                    postObject.getString("thumbnail")));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return ou_response;
        }

        @Override
        protected void onPostExecute(String result) {
            CustomProcessDialog.dissmis();
            if (result != null) {
                bus.post(infoModels);
            }
        }
    }
}

如何解决此问题,并在上​​面添加代码时,显示10个帖子并运行成功应用程序?感谢

3 个答案:

答案 0 :(得分:0)

&#34;后&#34;在您的服务器响应中使用索引5没有&#34; martial-frontpage-blog&#34;在&#34; thumbnail_images&#34;中,因此您的解析周期只会停止并丢弃异常。

要解决此问题 - 请使用optJSONObject();

imagesPair = images.optJSONObject("...");
并检查
null

答案 1 :(得分:0)

另一个时刻) 修复你的周期

for (int i = 0; i <= infoModels.size(); i++) {
for (int i = 0; i < postsArray.length(); i++) {
在您当前的实现周期中,异常停止工作)

答案 2 :(得分:0)

如何在这里使用Gson

首先,添加build.gradle这个

dependencies {
    compile 'com.google.code.gson:gson:2.4'
    //your all other dependencies
}

第二,创建类PostsResponse并在其中写入

package your.package.here;

import android.text.TextUtils;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;

public class PostsResponse {
    private static final String DEFAULT_IMAGE_URL = "put your default image url here";
    public static class Post {
        @SerializedName("id")
        private int mId;
        @SerializedName("title")
        private String mTitle;
        @SerializedName("content")
        private String mContent;
        @SerializedName("thumbnail")
        private String mThumbnail;
        @SerializedName("thumbnail_images")
        private Images mImages;

        public static class Images {
            @SerializedName("martial-frontpage-blog")
            private String mMartialFrontpageBlogUrl;

            public String getMartialFrontpageBlogImage() {
                return TextUtils.isEmpty(mMartialFrontpageBlogUrl) ?
                        DEFAULT_IMAGE_URL :
                        mMartialFrontpageBlogUrl;
            }
        }

        public int getId() {
            return mId;
        }

        public String getTitle() {
            return mTitle;
        }

        public String getContent() {
            return mContent;
        }

        public String getThumbnail() {
            return mThumbnail;
        }
        public String getMartialFrontpageBlogImage() {
            return mImages.getMartialFrontpageBlogImage();
        }
    }
    @SerializedName("posts")
    private ArrayList<Post> mPosts;

    public ArrayList<Post> getPosts() {
        return mPosts;
    }
}

并从

更改MainDataInfo的部分内容
       if (ou_response != null) {
            try {
                JSONObject postObj = new JSONObject(ou_response);
                JSONArray postsArray = postObj.getJSONArray("posts");
                infoModels = new ArrayList<>();

                for (int i = 0; i <= infoModels.size(); i++) {
                    JSONObject postObject = (JSONObject) postsArray.get(i);
                    int id = postObject.getInt("id");
                    String title = postObject.getString("title");
                    Log.d("Data", "Post id: " + id);
                    Log.d("Data", "Post title: " + title);

                    JSONObject images=postObject.getJSONObject("thumbnail_images");
                    JSONObject imagesPair=images.getJSONObject("martial-frontpage-blog");

                    //Use the title and id as per your requirement
                    infoModels.add(new MainDataModel(
                            postObject.getInt("id"),
                            postObject.getString("title"),
                            postObject.getString("content"),
                            postObject.getString("thumbnail")));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

到这个新的

        if (!TextUtils.isEmpty(ou_response)) {
            try {
                PostsResponse postsResponse = new Gson().fromJson(ou_response, PostsResponse.class);

                infoModels = new ArrayList<>();
                for (PostsResponse.Post post : postsResponse.getPosts()) {
                    infoModels.add(new MainDataModel(
                            post.getId(),
                            post.getTitle(),
                            post.getContent(),
                            post.getThumbnail())
                    );
                    //// TODO: 26.04.16 use post.getMartialFrontpageBlogImage()
                    //// as you want here
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

不要忘记正确填写DEFAULT_IMAGE_URL和包裹 并查看TODO部分 随意向Post类添加新字段并为其提供getter

结束)