Prince Hack Prince Hack - 6 months ago 291
JSON Question

Parsing JSONArray within JSONObject with volley in android

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

Answer

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