2017-06-18 72 views
0

我目前正在使用Yelp Fusion API來檢索業務信息。到目前爲止,我已經能夠得到我的POST請求的響應,但只能得到像輸出一樣的整個JSON。有什麼方法可以讓我過濾我的結果嗎?所以只需要檢索一個特定的鍵值和JSON輸出中的值。到目前爲止我的代碼如下所示:處理POST回覆

try { 
     String req = "https://api.yelp.com/v3/businesses/search?"; 
     req += "term=" + term + "&location=" + location; 
     if(category != null) { 
      req += "&category=" + category; 
     } 
     URL url = new URL(req); 
     HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); 
     con.setRequestMethod("GET"); 
     con.setRequestProperty("Authorization", "Bearer " + ACCESSTOKEN); 

     BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); 
     StringBuffer buffer = new StringBuffer(); 

     String inputLine = reader.readLine(); 
     buffer.append(inputLine); 
     System.out.println(buffer.toString()); 


     reader.close(); 

    } catch (Exception e) { 
     System.out.println("Error Connecting"); 
    } 

感謝

回答

0

滾你自己!你不能改變響應給你的詳細程度(除非API有這個功能),但你當然可以從響應中濾除你不需要的東西。

爲了說明,我拿了this的迴應。

{ 
    "terms": [ 
    { 
     "text": "Delivery" 
    } 
    ], 
    "businesses": [ 
    { 
     "id": "YqvoyaNvtoC8N5dA8pD2JA", 
     "name": "Delfina" 
    }, 
    { 
     "id": "vu6PlPyKptsT6oEq50qOzA", 
     "name": "Delarosa" 
    }, 
    { 
     "id": "bai6umLcCNy9cXql0Js2RQ", 
     "name": "Pizzeria Delfina" 
    } 
    ], 
    "categories": [ 
    { 
     "alias": "delis", 
     "title": "Delis" 
    }, 
    { 
     "alias": "fooddeliveryservices", 
     "title": "Food Delivery Services" 
    }, 
    { 
     "alias": "couriers", 
     "title": "Couriers & Delivery Services" 
    } 
    ] 
} 

如果我們只對名稱中含有Delfina的企業感興趣,我們可以執行以下操作。

JSONObject jsonResponse = new JSONObject(response); 
JSONArray businessesArray = jsonResponse.getJSONArray("businesses"); 
for (int i = 0; i < businessesArray.length(); i++) { 
    JSONObject businessObject = businessesArray.getJSONObject(i); 
    if (businessObject.get("name").toString().contains("Delfina")) { 
     //Do something with this object 
     System.out.println(businessObject); 
    } 
} 

其輸出(如預期)

{"name":"Delfina","id":"YqvoyaNvtoC8N5dA8pD2JA"} 
{"name":"Pizzeria Delfina","id":"bai6umLcCNy9cXql0Js2RQ"} 

我利用了org.json包在這裏,這是一個很簡單的一個,但足以讓你開始的!