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

时间:2016-05-26 12:15:43

标签: android arrays json android-volley jsonobject

我有这种情况 在服务器端有一些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

2 个答案:

答案 0 :(得分:3)

首先创建模型:

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;

in 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){
            }

排球: 在app类中:

private VolleyServiceSingleton mVolleySingleton;
private RequestQueue mVolleyApiClient;

on create:

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);

答案 1 :(得分:2)

这是一个错字或其他东西,但你的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);