2012-10-02 70 views
0

我以這種形式獲得響應我如何解析以下內容?

到目前爲止我嘗試下面的代碼 (全響應),但得到的錯誤

private String connect(String url) { 

    HttpClient httpclient = new DefaultHttpClient(); 
    HttpGet httpget = new HttpGet(url); 
    HttpResponse response; 
    String returnString = null; 
    try { 
     response = httpclient.execute(httpget); 
     if (response.getStatusLine().getStatusCode() == 200) { 
      HttpEntity entity = response.getEntity(); 
      if (entity != null) { 

       InputStream instream = entity.getContent(); 

       String res = convertStreamToString(instream); 

       JSONObject jsonObj = new JSONObject(res); 

       String f = jsonObj.getString("Result"); 

       f = f.trim(); 

       System.out.println("!!!!!!!!!!!!!!! "+f); 

       String s= jsonObj.getString("About"); 
       System.out.println("@@@@@@ "+s); 

       JSONArray get = jsonObj.getJSONArray("Result"); 



       // lets loop through the JSONArray and get all the items 
       for (int i = 0; i < get.length(); i++) { 
        // printing the values to the logcat 
        System.out.println("&&&&&&&&&&"+get.getJSONObject(i).getString("About").toString()); 
        System.out.println("&&&&&&&&&&"+get.getJSONObject(i).getString("AboutMeText").toString()); 
       } 



       instream.close(); 
      } 
     } else { 
      returnString = "Unable to load page - " 
        + response.getStatusLine(); 
     } 
    } catch (IOException ex) { 
     returnString = "Connection failed; " + ex.getMessage(); 
    } catch (JSONException ex) { 
     returnString = "JSON failed; " + ex.getMessage(); 
    } 
    return returnString; 
} 

private static String convertStreamToString(InputStream is) { 
    BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
    StringBuilder sb = new StringBuilder(); 

    String line = null; 
    try { 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      is.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    return sb.toString(); 
} 

每次我試圖解析它,它給了我JSON未能例外,說沒有價值.. 請讓我知道,如果我在這裏犯任何錯誤。

+0

,而不是你convertstremtostring,有EntityUtils.toString (脫離主題,抱歉) – njzk2

+1

這是一個無效的JSON字符串。使用http://www.jsonlint.org/ – Rajesh

+0

進行檢查在你的json中,我沒有看到對象中的任何字符串,該鍵將是GetConfigResult。這對我來說似乎合乎邏輯。我看不出問題在哪裏。 – njzk2

回答

1

JSON是無效的你想要嗎?

{ 
"Result": [ 
    { 
     "About": "", 
     "AboutMeText": {} 
    } 
] 
} 
+0

之後關於它就像 「AboutMeText」:[{}] – Shrikant

0

更簡單的方法是使用GSON。 (從內存中的所有代碼,所以......)

{Result: ["{"About":"","AboutMeText":[{}]]}我想創建一個類

public class Result { 
private String About; 
private String AboutMeText; 
    //getters and setters 
} 

然後以反序列化

Gson gson = new Gson(); 
Result result = gson.fromJson(jsonString, Result.class);