处理POST响应

时间:2017-06-18 22:30:29

标签: java json yelp

我目前正在使用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");
    }

由于

1 个答案:

答案 0 :(得分: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包,这是一个非常简单的包,但足以让你入门!