2014-04-24 3 views
0

내 응용 프로그램에서 올바르게 표시되도록하는 데 문제가 있습니다. JSON을 이와 같이 구문 분석 할 수 없다고 알려줍니다. 다음은이를 수행하는 코드입니다.URL에서 JSON 데이터를 파싱 할 수 없습니다.

private class SearchActivity2 extends AsyncTask<Void, Void, String> { 

    @Override 
    protected String doInBackground(Void... voids) { 
     String result = ""; 
     String s = ""; 
     InputStream isr = null; 
     HttpClient httpclient = null; 
     try { 
      httpclient = new DefaultHttpClient(); 
     } catch (Exception ex) { 
      //show.setText(ex.getMessage()); 
      System.exit(1); 
     } 
     HttpGet httpget = null; 
     try { 
      httpget = new HttpGet("http://deanclatworthy.com/imdb/?q=" + search); 
      //System.out.println("http://deanclatworthy.com/imdb/?q=" + search); 
     } catch (IllegalArgumentException ex) { 
      //show.setText(ex.getMessage()); 
      System.exit(1); 
     } 
     HttpResponse response = null; 

     try { 
      response = httpclient.execute(httpget); 
     } catch (IOException ex) { 
      //show.setText(ex.getMessage()); 
      System.exit(1); 
     } 

     try { 
      HttpEntity entity = response.getEntity(); 
      isr = entity.getContent(); 
     } catch (IOException ex) { 
      //show.setText(ex.getMessage()); 
      System.exit(1); 
     } catch (IllegalStateException ex) { 
      //show.setText(ex.getMessage()); 
      System.exit(1); 
     } 

     //convert response to string 
     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(isr, "iso-8859-1"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      isr.close(); 

      result = sb.toString(); 
     } catch (Exception e) { 
      Log.e("log_tag", "Error converting result " + e.toString()); 
     } 

     //parse json data 
     try { 

      JSONArray jArray = new JSONArray(result); 

      for (int i = 0; i < jArray.length(); i++) { 
       JSONObject json = jArray.getJSONObject(i); 
       s = s + 
         "Title : " + json.getString("title") + "\n" + 
         "Rating : " + json.getString("rating") + "\n"; 
      } 

      //show.setText(s); 
      return s; 
     } catch (Exception e) { 
      //TODO: handle exception 
      Log.e("log_tag", "Error Parsing Data " + e.toString()); 
     } 

     return s; 
    } 

    protected void onPostExecute(String s){ 
     showSearch.setText(s); 
    } 
} 

지금은 해당 웹 사이트의 제목과 등급을 표시하려고합니다. 이 경우 사용자가 입력 한 내용은 http://deanclatworthy.com/imdb/?q= +가됩니다. 따라서 http://deanclatworthy.com/imdb/?q=The+Incredible+Hulk이 작동합니다. 04-24 14 : 34 : 56.009 11886-12595/com.android.movies E/log_tag : 당신이 그것을 할 만 할 수있을 때

Error Parsing Data org.json.JSONException: Value {"series":0,"imdbid":"tt3628580","genres":"Animation,Comedy","imdburl":"http://www.imdb.com/title/tt3628580/","votes":"126","runtime":"21min","country":"n/a","stv":1,"languages":"English","title":"The Most Interesting Man in the World","cacheExpiry":1398972896,"year":"132014","usascreens":0,"rating":"6.9","ukscreens":0} of type org.json.JSONObject cannot be converted to JSONArray

+0

나는 그 결과가 배열이 아니라고 생각합니다 ... 아마 내가 전에 json을 사용하려고했기 때문에 ... 그것에 대해 읽었습니다 ... – Selvin

답변

0

왜 모두 통과 여기

는 로그 캣 오류입니다 이 간단한 단계.

1 단계 : 연결을 설정하고 json을 얻으십시오.

public String loadJSON(String someURL) { 

     String json = null; 
     HttpClient mHttpClient = new DefaultHttpClient(); 
     HttpGet mHttpGet = new HttpGet(someURL); 

     try { 

      HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet); 
      StatusLine statusline = mHttpResponse.getStatusLine(); 
      int statuscode = statusline.getStatusCode(); 
      if (statuscode != 200) { 

       return null; 

      } 
      InputStream jsonStream = mHttpResponse.getEntity().getContent(); 

      BufferedReader reader = new BufferedReader(
        new InputStreamReader(jsonStream)); 

      StringBuilder builder = new StringBuilder(); 
      String line; 

      while ((line = reader.readLine()) != null) { 

       builder.append(line); 

      } 

      json = builder.toString(); 

     } catch (IOException ex) { 

      ex.printStackTrace(); 

      return null; 
     } 
     mHttpClient.getConnectionManager().shutdown(); 
     return json; 

    } 

다음 단계 :

참고 :이 같은 JSON을로드하는 방법을 사용 당신은 어떤 URL로 연결하기 위해 위의 방법을 사용하여 JSON을 얻을 수 있습니다.

public void ParseJSON(String URL){ 

     try{ 

      JSONObject mainJSONObject = new JSONObject(loadJSON(URL)); 
      //If want just that particular block of information. 
      /*String getTitle = mainJSONObject.getString("title"); 
      String Country = mainJSONObject.getString("country");*/ 


      for(int i = 0;i<mainJSONObject.length();i++){//If you want all the data from the json. 

       String getTitle = mainJSONObject.getString("title"); 
       String Country = mainJSONObject.getString("country"); 
       //Rest you will figure it out. 


      } 

     }catch (Exception e){ 

      e.printStackTrace(); 

     } 

    } 

다음 단계 : 사용 AsyncTask를 백그라운드에서 물건을로드합니다.

public class someTask extends AsyncTask<Void,Void,Void>{ 

     ProgressDialog pDialog; 
     Context context; 
     String URL; 

     public someTask(Context context, String someURL){ 

      super(); 
      this.context = context; 
      this.URL = someURL; 

     } 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(context); 
      pDialog.setMessage("Loading files..."); 
      pDialog.setIndeterminate(true); 
      pDialog.setMax(100); 
      pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); 
      pDialog.setCancelable(true); 
      pDialog.show(); 
     } 

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

      ParseJSON(URL); 
      return null; 
     } 

     @Override 
     protected void onPostExecute(Void aVoid) { 
      super.onPostExecute(aVoid); 
      pDialog.dismiss(); 
     } 
    } 

마지막 단계 : 그냥 같이) (하지 OnCreate 작업을 실행합니다 (

새로운 someTask (문맥, your_url_you_want_to_execute) .Execute를);

희망이 솔루션은 쉽습니다. Lemme 그것이 작동 알아. 행운을 빌어 요 .. :

+0

약간의 조정이있을 수 있습니다 당신이 만들고자하는 코드에서. 다시 한번, 이것은 단지 문제를 해소하는 것입니다. – mike20132013

+0

작동하는 것처럼 보이지만 구문 분석 결과를 TextView로 설정해야합니다. – user3516585

+0

pDialog.dismiss() 전에; 다음과 같이 onPostExecute()에서 textview를 설정하면됩니다. your_text_view.setText (사용자의 Json 값 .i.e. 값을 가져 오는 문자열). – mike20132013

관련 문제