如何在Android中解析嵌套的JSON响应

时间:2016-06-06 10:59:46

标签: android json xml

我有这个JSON响应,我需要解析它。我该怎么做。

我有

中的整个json
JSONObject response = new JSONObject(result);

如何从下面的响应中解析所有JSON数组和字符串。

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

我是JSON解析的新手,有人可以写完整个代码。 感谢

2 个答案:

答案 0 :(得分:3)

使用以下功能。只需传递您的网址。

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

创建数据模型ImagesDataModel.class

public class QuestionDataModel {

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

}

和两个子列表类

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

}

答案 1 :(得分:0)

你需要做的事情

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

}

您的Activity类中的NetCheck.java

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也在Activity类

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

在Gradle中添加以下行

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

注意:如果数据是从服务器添加URL地址检索的,如果从localhost添加模拟器和移动设备的系统IP地址,请自行检查谷歌