2016-06-06 13 views
0

나는이 JSON 응답을 가지고 있으며이를 구문 분석해야한다. 내가 어떻게 해.안드로이드에서 중첩 JSON 응답을 구문 분석하는 방법

은 내가 응답 아래에서 모든 JSON 배열과 문자열을 구문 분석 할 수있는 방법

JSONObject response = new JSONObject(result); 

의 전체 JSON이있다.

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

저는 JSON 구문 분석을 처음 사용 했으므로 누군가 전체 코드를 작성하십시오. 감사

+2

사용'gson'->은 https ://blog.ajduke.in/2013/07/28/getting-started-with -google-gson/.. !! – AndiGeeky

+0

또 하나의 요점 -> 유효한'json' here .. !! – AndiGeeky

답변

0

것들 당신은 또한 작업 클래스

에서 활동 클래스

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에

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을 할 필요가 Gradle을

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

추가 다음 줄

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

참고 : 로컬 호스트에서 에뮬레이터를위한 시스템 IP 주소를 추가하고 Google 모바일

에서
3

사용을 직접 확인하면 데이터는 서버 추가 URL 주소에서 검색하는 경우 다음 기능. 그냥 귀하의 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); 
} 

데이터 모델 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; 

}