在 android 中使用 volley 解析 JSONObject 中的 JSONArray

Parsing JSONArray within JSONObject with volley in android

我这里有情况 在服务器端有一些 json 代码...这是 json

的一部分

{
"status":"ok",
"count":10,
"count_total":88,
"pages":9,
"posts":
[{
"id":1530,
"type":"post",
"slug":"slug",
""url":"url",
"status":"publish",
"title":"title",
"title_plain":"sth",
"content":"some content",
"modified":"2016-05-22 20:21:47",
"categories":[{"blah":"blah"}]
}]
}

我想在 "posts" 数组下使用 "content",而 volley 不允许我在 jsonobject 中使用 jsonarray。

这是我的部分代码:

JsonObjectRequest obreq = new JsonObjectRequest(Request.Method.GET, url, new 

Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            try {
                JSONObject obj = response.getJSONObject("posts");
            
                
            }
           JSONcatch (JSONException e) {
                
                e.printStackTrace();
            }
        }
    },null);

抱歉我无法插入我的代码片段...

Tnx

这是打字错误还是什么,但是你的 JSON 无效你在这里有两个双引号 ""url":"url"。只删除一个。

只需这样做:

JsonObjectRequest obreq = new JsonObjectRequest(Request.Method.GET, url, new

            Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    try {
                        JSONArray obj = response.getJSONArray("posts");

                        for (int i = 0; i < obj.length(); i++) {

                            JSONObject jsonObject = obj.getJSONObject(i);

                            int id = jsonObject.getInt("id");

                            String type = jsonObject.getString("type");

                            // retrieve the values like this so on..

                        }

                    }
                    catch (JSONException e) {

                        e.printStackTrace();
                    }
                }
            },null);

首先创建模型:

public class CategoryModel
{
    public String blah;
}

public class PostModel
{
    public int id;
    public String type;
    public String slug;
    public String url;
    public String status;
    public String title;
    public String title_plain;
    public String content;
    public String modified;
    public List<CategoryModel> categories;
}

public class PostsModel
{
    public String status;
    public int count;
    public int count_total;
    public int pages;
    public List<PostModel> posts;
}

然后使用 gson;

在gradle中:

compile 'com.google.code.gson:gson:2.4'

然后在代码中获取您的对象:

JSONObject json;
Gson gson = new Gson();
            try {
                json = new JSONObject(yourJsonString)
                PostsModel result = gson.fromJson(json, PostsModel.class);
                return result; // this is your deserialized response object
            }catch(Exception e){
            }

截击: 在应用中 class:

private VolleyServiceSingleton mVolleySingleton;
private RequestQueue mVolleyApiClient;

创建时:

mVolleySingleton = VolleyServiceSingleton.getInstance();
mVolleyApiClient = mVolleySingleton.gerRequestQueue();

字符串请求:

class VolleyStringRequest extends StringRequest
    {
        private Map<String, String> mParams;
        public VolleyStringRequest(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener, Map<String, String> requestParams) {
            super(method, url, listener, errorListener);
            mParams = requestParams;
            afterRequestErrorRunnable = null;
            Log.e("Request",url);
        }

        @Override
        protected VolleyError parseNetworkError(VolleyError volleyError) {
            if(volleyError.networkResponse != null && volleyError.networkResponse.data != null){
                try {
                    Log.e("errorResponse", new String( volleyError.networkResponse.data, "utf-8" ));
                }catch(Exception e){

                }


            }
            return super.parseNetworkError(volleyError);
        }

        @Override
        public RetryPolicy getRetryPolicy() {
            DefaultRetryPolicy retryPolicy = new DefaultRetryPolicy(
                    TIMEOUT_IN_MILLISECONDS,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
            return retryPolicy;
        }

        @Override
        public Map getHeaders() throws AuthFailureError {
            Map headers = new HashMap();
            headers.put("Accept-Charset","utf-8");
            //headers.put("Accept", RITEAID_HTTP_CONTENT_TYPE);
            return headers;
        }

        @Override
        public Map<String, String> getParams() {
            return mParams;
        }

    }

和请求(这个必须定制):

HashMap<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("sign_in_username_email", Utils.nullToStringOrString(username));
        paramMap.put("sign_in_password", password != null ? Utils.passwordConvert(password) : "");
        paramMap.put("key", Constants.API_KEY);

        mResponseHandler = getResponseHandler(requestUrl, positiveResponseFunc, inClass);
        VolleyStringRequest request = new VolleyStringRequest(Request.Method.POST, getFinalUrl(requestUrl, null), getResponseHandler(requestUrl, positiveResponseFunc, inClass), createErrorListener(context, progress), paramMap);
        request.setRetryPolicy(mRetryPolicy);
        request.setTag(REQUEST_TAG);
        mVolleyApiClient.add(request);