2012-05-25 64 views

回答

0

如果您需要標準程序,那麼您需要使用JSONObjectJSONArray來解析響應。但是,當您的響應字符串包含複雜結構時,它很模糊和麻煩。爲了處理這種複雜的響應,最好解析爲Gson,Jackson或任何其他庫。

0

下面的代碼應該給你一個出發點,只是在活動/服務類中使用它。它從一個URL(web服務)獲取數據,並將其轉換爲可以使用的JSON對象。

StringBuilder stringBuilder = new StringBuilder(); 
HttpClient client = new DefaultHttpClient(); 
HttpGet httpGet = new HttpGet(***Put your web service URL here ***) 
try 
{ 
    HttpResponse response = client.execute(httpGet); 
    StatusLine statusLine = response.getStatusLine(); 
    int statusCode = statusLine.getStatusCode(); 
    if (statusCode == 200) 
    { 
     HttpEntity entity = response.getEntity(); 
     InputStream content = entity.getContent(); 
     BufferedReader reader = new BufferedReader(
     new InputStreamReader(content)); 
     String line; 
     while ((line = reader.readLine()) != null) 
     { 
      stringBuilder.append(line); 
     } 
    } 
} 
catch (ClientProtocolException e) 
{ 
    e.printStackTrace(); 
} 
catch (IOException e) 
{ 
    e.printStackTrace(); 
} 

//Turn string JSON into object you can process 
JSONArray jsonArray = new JSONArray(stringBuilder.toString()); 
for (int i = 0; i < jsonArray.length(); i++) 
{ 
    //Get Each element 
    JSONObject jsonObject = jsonArray.getJSONObject(i); 
    //Do stuff 
} 
2

這是最好的方式來檢索JSON數據並解析它,我已經在我的項目中使用它,它工作得很好。看看這個Tutorial(源代碼也可用)。 如果您使用JSON,您肯定會需要Google gson庫將Java對象轉換爲其JSON表示形式。您可以從here下載它。