2017-06-18 40 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包在这里,这是一个很简单的一个,但足以让你开始的!