0

i have situation here have some json code in the server side ... here's a part of 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"}]
}]
}

i want "content" under the "posts" array and volley wouldn't let me use jsonarray inside jsonobject .

here's a part of my codes :

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

sorry for the snippet i couldn't insert my code ...

Tnx

Prince Hack
  • 25
  • 1
  • 5

2 Answers2

3

Is that a typo or something but your JSON is invalid you are having two double quotes here ""url":"url". Just remove one.

Just do this :

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);
Janki Gadhiya
  • 4,492
  • 2
  • 29
  • 59
3

First create Models:

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

then use gson;

in gradle:

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

then in code get your object:

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

Volley: in app class:

private VolleyServiceSingleton mVolleySingleton;
private RequestQueue mVolleyApiClient;

on create:

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

String request:

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

    }

and request (this must be customized):

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);
Stepan Maksymov
  • 2,618
  • 19
  • 31
  • tnx Stepan how can i convert it to volley library ? i have to get json code from the internet – Prince Hack May 26 '16 at 12:47
  • tnx Stepan how can i convert it to volley library ? i have to get json code from the internet – Prince Hack May 26 '16 at 12:49
  • create VolleySingleton in your appclass and then get instance of it, then make class which will make calls, then on respond you will get json string, deserialization is sometimes also hard task so deserialization must be also in async task, and you can make interfaces in your class and realize them in activity, and when data deserialized then you can run interface with data ready and catch them in your activity – Stepan Maksymov May 26 '16 at 13:01
  • updated answer, hard to explain all coz my apiclass is universal with deserialization models pass as parameter. – Stepan Maksymov May 26 '16 at 13:08