2014-04-07 7 views
1

Android에서 HTTP를 전송하는 JSON 형식 파일을 수신하려고합니다. 하지만 그 동안 파일 형식이 잘못되었다고 생각합니다.Android에서 HTTP 요청에서 JSON을 가져올 수 없습니다.

@Override 
     protected String doInBackground(String... params) { 
      StringBuilder builder = new StringBuilder(); 
      try { 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 

       URI website = new URI(params[0]); 

       HttpGet request = new HttpGet(); 
       request.setHeader("Content-type", "application/json"); 
       request.setURI(website); 
       HttpResponse httpResponse = httpClient.execute(request); 
       HttpEntity entity = httpResponse.getEntity(); 
       InputStream content = entity.getContent(); 
       BufferedReader reader = new BufferedReader(new InputStreamReader(content)); 
       String line; 
       while ((line = reader.readLine()) != null) { 
        System.out.println(line); 
        builder.append(line); 
       } 
      } 
      catch(Exception e){ 
       Log.e("http", e.toString()); 
      } 

      return builder.toString(); 
     } 


@Override 
     protected void onPostExecute(String result) { 
      try { 
       JSONObject jObject = new JSONObject(result); 
       txt.setText((String) jObject.get("shortName")); 
      } catch (JSONException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      //txt.setText(result); 
     } 

JSON 파일은 다음과 같이이다 :

{"lectiveSemesters":[{"lectiveSemesterId":1,"shortName":"0910i","startYear":2009,"term":1,"termName":"Fall","_links":{"self":"http://thoth.cc.e.ipl.pt/api/v1/lectivesemesters/1","root":"http://thoth.cc.e.ipl.pt/api/v1"}},{"lectiveSemesterId":2,"shortName":"0910v","startYear":2009,"term":2,"termName":"Spring","_links":{"self":"http://thoth.cc.e.ipl.pt/api/v1/lectivesemesters/2","root":"http://thoth.cc.e.ipl.pt/api/v1"}},{"lectiveSemesterId":3,"shortName":"1011i","startYear":2010,"term":1,"termName":"Fall","_links":{"self":"http://thoth.cc.e.ipl.pt/api/v1/lectivesemesters/3","root":"http://thoth.cc.e.ipl.pt/api/v1"}}, 
... 
... 
"_links":{"self":"http://thoth.cc.e.ipl.pt/api/v1/lectivesemesters"}} 

이 파일의 단지 부분의 코드는 다음과 같다.

내가 잘못 했나요? JSON 형식으로 수신하기 위해 헤더를 포함했습니다.

+0

JSON 형식에 따르면 lectiveSemesters의 값은 배열입니다. 그래서 배열의 각 항목에 대해 JSONArray를 가져와야합니다. shortName에 대한 값을 얻을 수 있습니다. –

+0

어떻게 처리합니까? JSONObject와 나는 JSONArray를 얻는다? –

답변

1

여기 있습니다. try{ JSONObject jObject = new JSONObject(result); JSONArray jarray = jObject.getJSONArray("lectiveSemesters"); for(int i = 0; jarray != null & i < jarray.length(); i++){ JSONObject jitem = (JSONObject) jarray.get(i); } } catch (Exception e){ }

+0

Worked! 알았어! JSON을 사용한 적이 없어서 약간 혼란 스러웠습니다. 고마워요! –

관련 문제