2014-12-03 61 views
1

我有這個寧靜的web服務http://firstsw.besaba.com/get_all.php?tab=doctors&cond=doc_id=2,我用Advanced Rest Client plugin for Chrome進行了測試,它運行良好。我想分析與Java代碼的JSON響應,所以我的代碼是:使用Java分析Json響應

import java.net.MalformedURLException; 
import java.net.URL; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import org.json.*; 

public class JsonArray { 

    public JsonArray() { 
     initJson(); 
    } 
    public void initJson() { 
     URL url; 
     try { 
      url = new URL("http://firstsw.besaba.com/get_all.php?tab=doctors&cond=doc_id=2");  
      JSONObject obj = new JSONObject(url); 
      String success = obj.getString("success"); 
      System.out.println(success+"/n"); 
      JSONArray arr = obj.getJSONArray("element"); 
      for(int i=0;i<att.length;i++){ 
       String doc_id = arr.getJSONObject(i).getString("doc_id"); 
       String doc_firstname = arr.getJSONObject(i).getString("doc_firstname"); 
       String doc_lastname = arr.getJSONObject(i).getString("doc_lastname"); 
       System.out.println("doc_id: "+doc_id+"/n"+"doc_firstname:"+doc_firstname+"/n"+"doc_lastname: "+doc_lastname); 
      } 
     } catch (MalformedURLException ex) { 
      Logger.getLogger(JsonArray.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 
} 

,但我得到的那些異常:

Exception in thread "main" org.json.JSONException: JSONObject["success"] not found. 
Exception in thread "main" org.json.JSONException: JSONObject["element"] not found. 
+0

請提供您的服務JSON響應。 – 2014-12-03 14:44:03

+0

@LuiggiMendoza使用提供的URL:http://pastebin.com/bRsMA5H2 :) – 2014-12-03 14:46:42

+1

您無法從URL創建JSONObject。作爲第一步,您應該獲得服務響應。 – mkrakhin 2014-12-03 14:47:29

回答

1

我覺得你的問題是

  url = new URL("http://firstsw.besaba.com/get_all.php?tab=doctors&cond=doc_id=2");  
     JSONObject obj = new JSONObject(url); 

你必須不要使用url作爲JSONObject(String)構造函數的參數。

你必須首先向服務器請求並獲得HTTP響應

對於你應該POST請求使用這樣的代碼

List<NameValuePair> params = new ArrayList<NameValuePair>(); 
params.add(new BasicNameValuePair("tab", "doctors")); 
params.add(new BasicNameValuePair("cond", "doc_id=2")); 

HttpParams httpParams = new BasicHttpParams(); 
HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); 
HttpProtocolParams.setContentCharset(httpParams, "UTF-8"); 
httpParams.setBooleanParameter("http.protocol.expect-continue", false); 

final String paramString = URLEncodedUtils.format(params, "UTF-8"); 
final String urlRequest = "http://firstsw.besaba.com/get_all.php?" + paramString; 
final HttpClient httpClient = new DefaultHttpClient(httpParams); 
final HttpGet httpGet = new HttpGet(urlRequest); 
final HttpResponse httpResponse = httpClient.execute(httpGet); 
String jsonString = EntityUtils.toString(response.getEntity(), HTTP.UTF_8); 
JSONObject jo = new JSONObject(jsonString); 

GET請求的JSON字符串

List<NameValuePair> params = new ArrayList<NameValuePair>(); 
params.add(new BasicNameValuePair("tab", "doctors")); 
params.add(new BasicNameValuePair("cond", "doc_id=2")); 

final HttpParams httpParams = new BasicHttpParams(); 
HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); 
HttpProtocolParams.setContentCharset(httpParams, "UTF-8"); 
httpParams.setBooleanParameter("http.protocol.expect-continue", false); 

final HttpClient httpClient = new DefaultHttpClient(httpParams); 
final HttpPost httpPost = new HttpPost("http://firstsw.besaba.com/get_all.php"); 
httpPost.setEntity(new UrlEncodedFormEntity(params)); 
final HttpResponse httpResponse = httpClient.execute(httpPost); 
String jsonString = EntityUtils.toString(response.getEntity(), HTTP.UTF_8); 
JSONObject jo = new JSONObject(jsonString); 
+0

我該怎麼做? – user3417644 2014-12-03 14:53:06

+0

已添加建議 – Deton 2014-12-03 14:59:24

+1

您忘記指定您正在使用Apache HttpComponents。 – 2014-12-03 15:01:53

2

我會推薦使用像Apache HttpComponentsUniRest這樣的庫來執行對外部服務器的http請求(GET,POST等)並返回適當的迴應。以下是使用UniRest的示例:

String url = "http://firstsw.besaba.com/get_all.php"; 
HttpResponse<JsonNode> jsonResponse = Unirest.get(url) 
    .queryString("tab", "doctor") 
    .queryString("cond", "doc_id=2") 
    .asJson(); 
String jsonContent = jsonResponse.getBody().toString(); 
//prints the JSON response 
System.out.println(jsonContent); 
//and you could create your JSON object from here 
JSONObject obj = new JSONObject(jsonContent); 
+0

我使用您的代碼,並且在我的類路徑中添加了UniRest.jar,但是我得到以下異常:「線程中的異常」main「java.lang.NoClassDefFoundError:org/apache/http/client/methods/HttpGet \t at com.mashape.unirest.request.BaseRequest.asJson(BaseRequest.java:68)' – user3417644 2014-12-03 15:15:56

+1

@ user3417644 unirest取決於其他庫。在這裏檢查:*不要忘記還要在*安裝/不使用Maven *部分的類路徑中安裝依賴項(org.json,httpclient 4.3.5,httpmime 4.3.5,httpasyncclient 4.0.2)。 – 2014-12-03 15:18:32

1

查看您的代碼行JSONObject obj = new JSONObject(url)有問題。
根據javadoc的url被視爲一個對象。
這不會給你想要的結果。
更好的辦法是先將json內容作爲字符串獲取。
替換此部分:

 url = new URL("http://firstsw.besaba.com/get_all.php?tab=doctors&cond=doc_id=2"); 

     String content = (String)url.getContent(); 
     JSONObject obj = new JSONObject(content); 
     String success = obj.getString("success"); 
     System.out.println(success+"/n"); 
     JSONArray arr = obj.getJSONArray("element"); 

看到,我發現這個信息的Javadoc: json.org

+0

異常:'java.lang.ClassCastException:sun.net.www.protocol.http.HttpURLConnection $ HttpInputStream不能轉換爲java.lang.String' – user3417644 2014-12-03 15:21:29