我目前正在使用Yelp Fusion API来检索业务信息。到目前为止,我已经能够获得对POST请求的响应,但只能获得完整的JSON输出。有什么方法可以让我过滤我的结果吗?所以只需要在JSON输出中检索一个特定的键和值。到目前为止,我的代码如下:
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");
}
谢谢
发布于 2017-06-19 07:39:57
滚你自己的!您不能更改响应提供给您的详细程度(除非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
包,这是一个非常简单的包,但足以让您入门!
https://stackoverflow.com/questions/44620144
复制相似问题