2014-07-21 10 views
0

웹 서버에서 전달 된 json 문자열을 구문 분석하고 키 문자열 배열로 변환하려고합니다. 결과는 "str [ID] = artist - title"과 같이 보이기를 바랍니다.Android Parse JSON 문자열에서 문자열 배열

다음은 json을 가져 와서 구문 분석을 시작하기 위해 사용하는 코드입니다.

   new Thread(new Runnable() { 
       public void run() { 
        try { 
         try { 
          HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client 
          HttpGet httpget = new HttpGet("http://somesite.net/some.php"); // Set the action you want to do 
          HttpResponse response = httpclient.execute(httpget); // Executeit 
          HttpEntity entity = response.getEntity(); 
          InputStream is = entity.getContent(); // Create an InputStream with the response 
          BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); 
          StringBuilder sb = new StringBuilder(); 
          String line = null; 
          while ((line = reader.readLine()) != null) // Read line by line 
           sb.append(line + "\n"); 


          String resString = sb.toString(); // Result is here 
          JSONObject json = new JSONObject(resString); 
          String[] array = new Gson().fromJson(resString, String[].class); 
          Log.e("TESTAPP", "SOME RES E " + array.toString()); 

          is.close(); // Close the stream 
         } 
         catch (Exception e) { 
          Log.e("TESTAPP", "SOME Catch Error E " + e.toString()); 
         } 
        } 
        catch (Exception e){ 
         Log.e("TESTAPP", "SOME Error" + e.getMessage()); 
        } 
       } 
      }).start(); 

은 일부 샘플 JSON을 파싱하려는 JSON 문자열에 오류가있다

{"item":{"artist":"Billy Idol","requestid":"42207","title":"Rebel Yell"}}{"item":{"artist":"Black Sunshine","requestid":"42208","title":"Once In My Life"}}{"item":{"artist":"Blackstreet","requestid":"42209","title":"Before I Let You Go"}}{"item":{"artist":"Black Sabbath","requestid":"42210","title":"Time Machine"}} 

답변

1

사용. {} 내부의 모든 문자열은 JSON 개체이며, 제공된 문자열에 다른 item 객체를 포함하는 객체있다 :

{ 
    "item": { 
    "artist": "Billy Idol", 
    "requestid": "42207", 
    "title": "Rebel Yell" 
    } 
} 

그리고 다른 item 개체가 포함 된 다음 또 다른 객체입니다.

{ 
    "item": { 
    "artist": "Black Sunshine", 
    "requestid": "42208", 
    "title": "Once In My Life" 
    } 
} 

잘못된 JSONString입니다. 구문 분석을 시도하기 전에 JSON String의 유효성을 검사하기 위해 http://jsonlint.com/과 같은 도구를 사용하는 것이 좋습니다.

+0

json을 수정 한 후 제대로 구문 분석하는 것이 훨씬 쉬워졌습니다. 감사! – Dandrews