2012-05-25 65 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下载它。