2013-08-08 5 views
0

웹 서비스에서 특정 데이터를 받기 위해 JSON 문자열을 인코딩하는 데 약간의 도움이 필요합니다. 이미 JSON 문자열을 표준 JSONParsser 클래스에서 볼 수있는 표준 방식으로 포맷하려고했지만 내 JSON 문자열이 유효하지 않아서 이전 질문에서 여기에서 볼 수 있다고 들었습니다. Converting a String to JSONObject 제 코드를 아무에게도 묻지 않습니다. 제 코드를 살펴보고 URL 매개 변수에 오류가 있는지 그리고 JSON 문자열을 인코딩하여 데이터를 수신해야 하는지를 묻는 것입니다. 이 웹 서비스.안드로이드 도움이 필요합니다 json

public class MainActivity extends Activity { 

    Button getanswer; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 



     Button getanswer = (Button) findViewById(R.id.button1); 
     getanswer.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) {  
      EditText et = (EditText) findViewById(R.id.editText1); 
      String searchTerm = et.getText().toString().trim();   
      Intent in = new Intent(MainActivity.this, ListView.class); 
      in.putExtra("TAG_SEARCH", searchTerm); 
      startActivity(in); 
     } 


     }); 
    }} 

의 ListView 활동 :

여기에 URL 링크는 http://developer.yahoo.com/answers/V1/questionSearch.html 매개 변수와 난 그냥이 질문에 https://stackoverflow.com/questions/18028570/yahoo-answers-json-parse

MainActivity를의 클래스가 아닌 JSON 데이터를보고 분석하기 위해 노력하고있어 데이터를 참조하는 것입니다

public class ListView extends ListActivity {  


    ArrayList<HashMap<String, String>> questionList;  

    final String TAG_RESULTS = "results"; 
    final String TAG_QUESTION_SUBJECT = "Subject"; 
    final String TAG_QUESTION_NUMANSWERS = "NumAnswers"; 
    final String TAG_QUESTION = "Question"; 
    final String TAG_QUESTION_CONTENT = "Content"; 
    final String TAG_QUESTION_CHOSENANSWER = "ChosenAnswer"; 
    final String TAG_ANSWERS = "Answers"; 
    final String TAG_ANSWER = "Answer";  
    final String TAG_ANSWERS_CONTENT = "Content";  

      JSONArray results; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.listview);  

     //questionList = new ArrayList<HashMap<String, String>>(); 



    new LoadAllData().execute(); 
     } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 

     if (resultCode == 100) { 
      Intent intent = getIntent(); 
      startActivity(intent); 
      finish(); 
     } 
    } 

    class LoadAllData extends AsyncTask<String, String, String> { 


     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      ProgressDialog pDialog; 
      pDialog = new ProgressDialog(ListView.this); 
      pDialog.setMessage("Loading Data. Please wait..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(false); 
      pDialog.show(); 
      if (pDialog != null && pDialog.isShowing()) pDialog.dismiss(); 

     } 

     protected String doInBackground(String... args) { 

      try { 
       Intent in = getIntent(); 
       String searchTerm = in.getStringExtra("TAG_SEARCH"); 
       String query = URLEncoder.encode(searchTerm, "utf-8"); 
       String URL = "http://answers.yahooapis.com/AnswerService/V1/questionSearch?appid=YahooDemo&query="+ query +"search_in=question&sort=relevance&results=25&output=json&callback=ws_results"; 
       JSONParsser jParser = new JSONParsser(); 
       JSONObject jObj = jParser.readJSONFeed(URL); 
       try { 
        results = jObj.getJSONArray(TAG_RESULTS); 

        for(int i = 0; i < results.length(); i++) { 
          JSONObject r = results.getJSONObject(i); 

          JSONObject Question = r.getJSONObject(TAG_QUESTION); 
          String Subject = Question.getString(TAG_QUESTION_SUBJECT); 
          String NumAnswers = Question.getString(TAG_QUESTION_NUMANSWERS); 
          String ChosenAnswers= Question.getString(TAG_QUESTION_CHOSENANSWER); 
          String Content = Question.getString(TAG_QUESTION_CONTENT); 

          //JSONObject Answers = Question.getJSONObject(TAG_ANSWERS); 
          //JSONObject Answer = Answers.getJSONObject(TAG_ANSWER); 
          //String Content1 = Answers.getString(TAG_ANSWERS_CONTENT); 

          questionList = new ArrayList<HashMap<String, String>>(); 

           HashMap<String, String> map = new HashMap<String, String>(); 

           map.put(TAG_QUESTION_SUBJECT, Subject); 
           map.put(TAG_QUESTION_NUMANSWERS, NumAnswers); 

           questionList.add(map); 

          } 



       } catch (JSONException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } catch (UnsupportedEncodingException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

       return TAG_RESULTS ; 



     } 
     @Override 
     protected void onPostExecute(String file_URL) { 

       ListAdapter adapter = new SimpleAdapter(getBaseContext(), questionList, 
         R.layout.listview, 
         new String[] { TAG_QUESTION_SUBJECT, TAG_QUESTION_NUMANSWERS }, new int[] { 
         R.id.Subject, R.id.NumAnswers }); 

       setListAdapter(adapter); 

       android.widget.ListView lv = getListView(); 

       lv.setOnItemClickListener(new OnItemClickListener() { 

        @Override 
        public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) { 
         // TODO Auto-generated method stub 

        } 

       });  

     }} 

    } 

JSONParsser :

public class JSONParsser { 

    InputStream is; 
    JSONObject jObj; 
    String json = ""; 
    public EditText et; 

    public JSONParsser() { 
    } 

    public JSONObject readJSONFeed(String URL) { 

     try{ 
     HttpClient client = new DefaultHttpClient(); 
     HttpPost request = new HttpPost(URL); 
     //request.setURI(website); 
     try { 
      HttpResponse response = client.execute(request); 
     HttpEntity httpEntity = response.getEntity(); 
     is = httpEntity.getContent(); 

     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "iso-8859-1"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      json = sb.toString(); 
     } catch (Exception e) { 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 

     try { 
      jObj = new JSONObject(json); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 

     Log.d("JSON String",json); 

     return jObj; 

     }finally{} 

    }{ 
    }} 

목 내 인쇄 된 JSON 문자열입니다 당신이 그것을 이해한다면 그것은 기본적으로 웹 서비스에서 오류 페이지를 반환 :

08-02 20:02:27.535: D/JSON String(795): <!doctype html public "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
08-02 20:02:27.535: D/JSON String(795): <html><head><title>Yahoo! - 404 Not Found</title><style> 
08-02 20:02:27.535: D/JSON String(795): /* nn4 hide */ 
08-02 20:02:27.535: D/JSON String(795): /*/*/ 
08-02 20:02:27.535: D/JSON String(795): body {font:small/1.2em arial,helvetica,clean,sans-serif;font:x-small;text-align:center;}table {font-size:inherit;font:x-small;} 
08-02 20:02:27.535: D/JSON String(795): html>body {font:83%/1.2em arial,helvetica,clean,sans-serif;}input {font-size:100%;vertical-align:middle;}p, form {margin:0;padding:0;} 
08-02 20:02:27.535: D/JSON String(795): p {padding-bottom:6px;margin-bottom:10px;}#doc {width:48.5em;margin:0 auto;border:1px solid #fff;text-align:center;}#ygma {text-align:right;margin-bottom:53px} 
08-02 20:02:27.535: D/JSON String(795): #ygma img {float:left;}#ygma div {border-bottom:1px solid #ccc;padding-bottom:8px;margin-left:152px;}#bd {clear:both;text-align:left;width:75%;margin:0 auto 20px;} 
08-02 20:02:27.535: D/JSON String(795): h1 {font-size:135%;text-align:center;margin:0 0 15px;}legend {display:none;}fieldset {border:0 solid #fff;padding:.8em 0 .8em 4.5em;} 
08-02 20:02:27.535: D/JSON String(795): form {position:relative;background:#eee;margin-bottom:15px;border:1px solid #ccc;border-width:1px 0;} 
08-02 20:02:27.535: D/JSON String(795): #s1p {width:15em;margin-right:.1em;} 
08-02 20:02:27.535: D/JSON String(795): form span {position:absolute;left:70%;top:.8em;}form a {font:78%/1.2em arial;display:block;padding-left:.8em;white-space:nowrap;background: url(http://l.yimg.com/a/i/s/bullet.gif) no-repeat left center;} 
08-02 20:02:27.535: D/JSON String(795): form .sep {display:none;}.more {text-align:center;}#ft {padding-top:10px;border-top:1px solid #999;}#ft p {text-align:center;font:78% arial;} 
08-02 20:02:27.535: D/JSON String(795): /* end nn4 hide */ 
08-02 20:02:27.535: D/JSON String(795): </style></head> 
08-02 20:02:27.535: D/JSON String(795): <body><div id="doc"> 
08-02 20:02:27.535: D/JSON String(795): <div id="ygma"><a href="http://us.rd.yahoo.com/404/*http://www.yahoo.com"><img 
08-02 20:02:27.535: D/JSON String(795): src=http://l.yimg.com/a/i/yahoo.gif 
08-02 20:02:27.535: D/JSON String(795): width=147 height=31 border=0 alt="Yahoo!"></a><div><a 
08-02 20:02:27.535: D/JSON String(795): href="http://us.rd.yahoo.com/404/*http://www.yahoo.com">Yahoo!</a> 
08-02 20:02:27.535: D/JSON String(795): - <a href="http://us.rd.yahoo.com/404/*http://help.yahoo.com">Help</a></div></div> 
08-02 20:02:27.535: D/JSON String(795): <div id="bd"><h1>Sorry, the page you requested was not found.</h1> 
08-02 20:02:27.535: D/JSON String(795): <p>Please check the URL for proper spelling and capitalization. If 
08-02 20:02:27.535: D/JSON String(795): you're having trouble locating a destination on Yahoo!, try visiting the 
08-02 20:02:27.535: D/JSON String(795): <strong><a 
08-02 20:02:27.535: D/JSON String(795): href="http://us.rd.yahoo.com/404/*http://www.yahoo.com">Yahoo! home 
08-02 20:02:27.535: D/JSON String(795): page</a></strong> or look through a list of <strong><a 
08-02 20:02:27.535: D/JSON String(795): href="http://us.rd.yahoo.com/404/*http://docs.yahoo.com/docs/family/more/">Yahoo!'s 
08-02 20:02:27.535: D/JSON String(795): online services</a></strong>. Also, you may find what you're looking for 
08-02 20:02:27.535: D/JSON String(795): if you try searching below.</p> 
08-02 20:02:27.535: D/JSON String(795): <form name="s1" action="http://us.rd.yahoo.com/404/*-http://search.yahoo.com/search"><fieldset> 
08-02 20:02:27.535: D/JSON String(795): <legend><label for="s1p">Search the Web</label></legend> 
08-02 20:02:27.535: D/JSON String(795): <input type="text" size=30 name="p" id="s1p" title="enter search terms here"> 
08-02 20:02:27.535: D/JSON String(795): <input type="submit" value="Search"> 
08-02 20:02:27.535: D/JSON String(795): <span><a href="http://us.rd.yahoo.com/404/*http://search.yahoo.com/search/options?p=">advanced search</a> <span class=sep>|</span> <a href="http://us.rd.yahoo.com/404/*http://buzz.yahoo.com">most popular</a></span> 
08-02 20:02:27.535: D/JSON String(795): </fieldset></form> 
08-02 20:02:27.535: D/JSON String(795): <p class="more">Please try <strong><a 
08-02 20:02:27.535: D/JSON String(795): href="http://us.rd.yahoo.com/404/*http://help.yahoo.com">Yahoo! 
08-02 20:02:27.535: D/JSON String(795): Help Central</a></strong> if you need more assistance.</p> 
08-02 20:02:27.535: D/JSON String(795): </div><div id="ft"><p>Copyright &copy; 2013 Yahoo! Inc. 
08-02 20:02:27.535: D/JSON String(795): All rights reserved. <a 
08-02 20:02:27.535: D/JSON String(795): href="http://us.rd.yahoo.com/404/*http://privacy.yahoo.com">Privacy 
08-02 20:02:27.535: D/JSON String(795): Policy</a> - <a 
08-02 20:02:27.535: D/JSON String(795): href="http://us.rd.yahoo.com/404/*http://docs.yahoo.com/info/terms/">Terms 
08-02 20:02:27.535: D/JSON String(795): of Service</a></p></div> 
08-02 20:02:27.535: D/JSON String(795): </div></body></html> 
+1

당신이 링크 한 질문에 대한 답변으로 : 게시물은 * JSON이 아닙니다. – dst

답변

2

귀하의 URL :

http://answers.yahooapis.com/AnswerService/V1/questionSearch 

올바른 URL :

http://answers.yahooapis.com/AnswersService/V1/questionSearch 

AnswerService의 차이는 AnswersService이어야합니다. 모든 쿼리 매개 변수는 앰퍼샌드로 구분하기 때문에

...&query="+ query +"search... 

...&query="+ query +"&search... 

해야합니다 당신은 또한 여기에 오류가 있습니다. Here is an example of the url in action. 그 id는 나에게 오류를 주었기 때문에 아마도 자신의 app id를 얻을 필요가 있음을 주목하라. 예를 들어 Yahoo에서 제공하는 데모 앱 ID를 사용하고있는 것 같습니다.

+0

이제 데이터를 반환하고 또한 내 새로운 질문 stackoverflow.com/questions/18138808/을 볼 수있다 고마워요. 그것은 여전히 ​​야후 대답에 관한 것입니다. 익숙하기 때문에 나는 당신이 나를 도울 수 있기를 바랬습니다. –

관련 문제