Amar Ilindra
Amar Ilindra

Reputation: 983

How to Parse a Nested JSON response in Android

I Have this JSON response and I need to parse it. How can I do it.

I have the the entire json in

JSONObject response = new JSONObject(result);

How can I parse all JSON arrays and strings from below response.

[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]

I'm new to JSON parsing, someone could please write the entire code. Thanks

Upvotes: 0

Views: 546

Answers (2)

Ahmad.Aslam90
Ahmad.Aslam90

Reputation: 74

Things you need to do

1--> Make JSON Parser seprate class for encoding and decoding JSON String.
2--> Make Aysnc class for JSON data downloading and extract in separate variables or in array with the help of JSON Parser class.
3--> perform Internet and server availability before downloading data by making class or method for it.  
4--> After successfully data receiving in OnpostExcecute() Method of Async class show data in UI elements.

JSONParser.java

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    public static String Result=null;

    public JSONParser()
    {

    }

    public static JSONObject makeHttpRequest(String url,String method, List<NameValuePair>  pair) {

        try {

            // check for request method
            if(method.equals("POST")){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(pair));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method.equals("GET")){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(pair, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, HTTP.UTF_8), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Result = json;
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        return jObj;
    }

}

NetCheck.java in your Activity class

public class NetCheck extends AsyncTask<String,Object,Boolean>
    {

        private ProgressDialog nDialog;
        NetworkInfo netInfo;

        @Override
        protected void onPreExecute() {

            nDialog = new ProgressDialog(NetCheck.this);
            nDialog.setTitle("Checking");
            nDialog.setMessage("Loading..");
            nDialog.setIndeterminate(false);
            nDialog.setCancelable(true);
            nDialog.show();
            super.onPreExecute();
        }

        @Override
        protected Boolean doInBackground(String... params) {

            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            netInfo = cm.getActiveNetworkInfo();

            if (netInfo != null && netInfo.isConnected()) {
                try {
                    URL url = new URL("http:/xxxxxxx");
                    HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                    urlc.setConnectTimeout(1000);
                    urlc.connect();
                    if (urlc.getResponseCode() == 200) {
                        return true;
                    }
                } catch (MalformedURLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                return true;
            }

            else
            {
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean th) {

            if (th)
            {
                nDialog.dismiss();
                new ProcessDataClass().execute();
            }

            else
            {

                new AlertDialog.Builder(NetCheck.this)
                        .setTitle("Record Not Found or Server is Busy")
                                //.setMessage("Are you sure you want to delete this entry?")
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // continue with delete
                                nDialog.dismiss();
                            }
                        })
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .show();
            }
            super.onPostExecute(th);
        }
    }

ProcessDataClass.java in also Activity class

 public class ProcessDataClass extends  AsyncTask<String, Object,Object>
{

    @Override
    protected String doInBackground(String... params) {

        JSONObject json;
        List<NameValuePair> pair = new ArrayList<>();

        //make ypur own pair for reciving data
        //pair.add(new BasicNameValuePair("id", String.valueOf(index)));

        json = JSONParser.makeHttpRequest("http://xxxx","GET",pair);
        Log.d("Route Response", json.toString());

        int success = 0;

        try {
            // Success TAG only deals with API response not neccessory depends on API extracting or from URL TAG's 
            success = json.getInt(TAG_SUCCESS);
        }

        catch (JSONException e) {
            e.printStackTrace();
        }

        try {

                if (success == 1) {

                    JSONArray jsonarray;
                    json = new JSONObject(JSONParser.Result);
                    JSONArray jArray = json.getJSONArray("your TAG");

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

                        jsonarray = jArray.getJSONArray(i);

                       //Do your Logic there 

                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {

           //Update UI as per your need          

            super.onPostExecute(o);
        }
    }
}

Add following line in Gradle

compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'

Note: if data is retrieving from server add URL address, if from localhost add System IP address for Emulator and for Mobile check yourself from google

Upvotes: 0

Sohail Yasin
Sohail Yasin

Reputation: 344

use following function .just pass your url.

  private void getData(String url) {
    pDialog = new ProgressDialog(this);
    pDialog.setMessage(getResources().getString(R.string.app_name));
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(true);
    pDialog.show();
    //   String url = "http://httpbin.org/html";
    Log.d("soh_into_get", url);

    jsonArray = new JsonArrayRequest(Request.Method.GET, url,
            new Response.Listener<JSONArray>() {

                @Override
                public void onResponse(JSONArray data) {
                    try {

                        Log.d("soh_json", String.valueOf(data));


                        for (int i = 0; i < data.length(); i++) {
                            JSONObject jObj = data.getJSONObject(i);
                            ImagesDataModel pModel = new ImagesDataModel();

                            pModel.image_id = jObj.getString("image_id");
                            Log.d("image_id", jObj.getString("image_id"));
                            JSONArray jsonArray = jObj.getJSONArray("comments");
                            for (int j = 0; j < jsonArray.length(); j++) {
                                JSONObject jObj1 = jsonArray.getJSONObject(j);
                                ChildListDataModel cModel = new ChildListDataModel();
                                cModel.comment_id = jObj1.getString("comment_id");
                                cModel.user_id = jObj1.getString("user_id");
                                cModel.comment = jObj1.getString("comment");
                                cModel.commented_on = jObj1.getString("commented_on");
                                pModel.childList.add(cModel);

                            }
                            JSONArray jsonArray = jObj.getJSONArray("likes");
                            for (int j = 0; j < jsonArray.length(); j++) {
                                JSONObject jObj1 = jsonArray.getJSONObject(j);
                                ChildListDataModel_like clModel = new ChildListDataModel_like();
                                clModel.like_id = jObj1.getString("like_id");
                                clModel.user_id = jObj1.getString("user_id");
                                clModel.liked_on = jObj1.getString("liked_on");
                                pModel.childList.add(clModel);

                            }


                            questionDataModel_List.add(pModel);
                            // setData();

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    pDialog.dismiss();
                    jsonArray = null;
                }


            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            //SetOffLineData();
            pDialog.dismiss();
            // Error handling
            System.out.println("Something went wrong!");
            error.printStackTrace();

        }
    });
    jsonArray.setRetryPolicy(new DefaultRetryPolicy(
            8000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));


    Volley.newRequestQueue(this).add(jsonArray);
}

create data model ImagesDataModel.class

public class QuestionDataModel {

public String image_id;
public List<ChildListDataModel> childList = new ArrayList<>();
public List<ChildListDataModel_like > childList2 = new ArrayList<>();

}

and two child list classes

public class ChildListDataModel {
public String comment_id;
public String user_id;
public String comment;
public String commented_on;

}

Upvotes: 3

Related Questions