1

I have a json response from server, attached below. I want to parse this response with volley in android. How do I parse the object(s) within the array.

  {
  "status": "ok",
  "source": "techcrunch",
  "sortBy": "top",
  "articles": [
    {
      "author": "Ingrid Lunden, Fitz Tepper",
      "title": "Confirmed: AT&T is buying Time Warner for $85.4B in cash and shares",
      "description": "After days of speculation, the deal is now official: AT&T is acquiring Time Warner for $85 billion in a mix of cash and shares, paving the way for..",
      "url": "http://social.techcrunch.com/2016/10/22/confirmed-att-is-buying-time-warner-for-85-4b-in-cash-and-shares/",
      "urlToImage": "https://tctechcrunch2011.files.wordpress.com/2016/10/946_432_newsroom_release_tw.jpg?w=764&h=400&crop=1",
      "publishedAt": "2016-10-23T00:02:34Z"
    },

I want to access the first object, and the next, and the next after that. Appreciate.

4
  • do you know how to use volley to get json from server? Commented Oct 23, 2016 at 2:47
  • can you tell me @RitikKumarAgrahari Commented Oct 23, 2016 at 2:55
  • i have posted the solution , have a look at it Commented Oct 23, 2016 at 3:34
  • - stackoverflow.com/questions/50452916/… Commented May 21, 2018 at 16:37

5 Answers 5

3

This should display a list of the titles

JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, url, null,
    new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            JSONArray jsonArray = null;
            try {
                jsonArray = response.getJSONArray("articles");
                for(int i=0; i<jsonArray.length(); i++){
                    JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                        Log.d(TAG, jsonObject.getString("title"));
                    }
                } catch (JSONException e) {
                        e.printStackTrace();
                }                       }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d(TAG, "Error: " + error.getMessage());
        }
   });
Sign up to request clarification or add additional context in comments.

2 Comments

Not working @Short answer. Returns a blank screen after run and response code 405 in log cat
Updated answer from Request.Method.POST to Request.Method.GET
0

first you have to add volley library using

compile 'com.mcxiaoke.volley:library-aar:1.0.0'

in build.grdle file like shown below

apply plugin: 'com.android.application'

android {
compileSdkVersion 24
buildToolsVersion "24.0.2"

defaultConfig {
    applicationId "com.iitism.ritik.popularmovies"
    minSdkVersion 15
    targetSdkVersion 24
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.1.1'
compile 'com.android.support:design:24.1.1'
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
compile 'com.squareup.picasso:picasso:2.5.2'
compile files('libs/YouTubeAndroidPlayerApi.jar')
}

Then u need a url to get json object after that u can follow below code to parse json

StringRequest stringRequest = new StringRequest(URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d("TAG",response);
            showJson(response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(MainActivity.this,error.getMessage(),Toast.LENGTH_SHORT).show();
        }
    });

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);


public void showJson(String response)
{
    Log.d("TAG",response);
    try {
        JSONObject jsonObject = new JSONObject(response);
        JSONArray jsonArray = jsonObject.getJSONArray("results");
        int n = jsonArray.length();
        for(int i=0;i<n;i++)
        {
            JSONObject movieObject = jsonArray.getJSONObject(i);
            String title = movieObject.getString("original_title");
            String poster_path = movieObject.getString("poster_path");
            String overView = movieObject.getString("overview");
            String releaseDate = movieObject.getString("release_date");
            String popularity = movieObject.getString("popularity");
            String voteAvg = movieObject.getString("vote_average");
            String id = movieObject.getString("id");
            movieList.add(new Movie(poster_path,title,overView,releaseDate,popularity,voteAvg,id));
            movieAdapter.notifyDataSetChanged();
        }
    } catch (JSONException e) {
        Toast.makeText(getApplicationContext(),"Not available",Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }
}

like in your json u want to parse "articles" array so u can use below code

JSONArray jsonArray = jsonObject.getJSONArray("articles");

int n = jsonArray.length();
    for(int i=0;i<n;i++)
    {
        JSONObject movieObject = jsonArray.getJSONObject(i);
        //do your work here
    }

Comments

0

First you check This APi is POST API or GET API. if this api is POST method then pass the parameter in the hashmap.and if it is the GET api then pass the parameter with the url. and below code is parsing your given json.

     StringRequest notificationrequest = new StringRequest(Request.Method.POST, YOUR_URL,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {



                            try {


                                JSONObject jObject = new JSONObject(response);
                                if (jObject.getString("status").equals("ok")) {

                                String source = jObject.getString("source");
                                String sortby = jObject .getString("sortBy");



                                    JSONArray jsonArray = jObject.getJSONArray("articles");
                                    for (int i = 0; i < jsonArray.length(); i++) {


                                        JSONObject jsonObject = jsonArray.getJSONObject(i);

                    String author = jsonObject.getString("author");
                    String title= jsonObject.getString("title");
                    String description= jsonObject.getString("description");
                    String url= jsonObject.getString("url");   
                    String urlToImage= jsonObject.getString("urlToImage");    
                    String publishedAt= jsonObject.getString("publishedAt");                                    




                                              }





                                } else {

                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {

                            Log.e("error", "" + volleyError.getMessage());


                        }
                    }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {

                    Map<String, String> params = new HashMap<String, String>();
                  //put your parameter in the hash map variable params if you using post request


                    return params;
                }
            };

            RequestQueue notificationqueue = Volley.newRequestQueue(getContext());

            notificationqueue.add(notificationrequest);

and don't forget the putting the gradle dependency of volley.

Comments

0

Try this way to get your result

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

            Response.Listener<JSONObject>() {

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

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

                            JSONObject jsonObject = obj.getJSONObject(i);



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

                            // check the other values like this so on..

                        }

                    }
                    catch (JSONException e) {

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

Comments

0
    public void onResponse(Object response) {
            JSONArray jsonArray = null;
            try {
            Log.e("status",((JSONObject)response).getString("status"));
            Log.e("source",((JSONObject)response).getString("source"));
            Log.e("sortBy",((JSONObject)response).getString("sortBy"));
            Log.e("articles",((JSONObject)response).getString("articles"));//Notice than the articles string could not be completly display in the Log if it is too long

                //if you want to browse the table of articles
                jsonArray = ((JSONObject)response).getJSONArray("articles");
                for (int i = 0 ; i < jsonArray.length() ; i++){
                    Log.e("Item "+i,jsonArray.getJSONObject(i).getString("source"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.