【发布时间】:2018-12-26 00:50:08
【问题描述】:
我正在为学校构建一个 java servlet 页面,我想在其中放置一个 API。到目前为止,我在使用 API 时遇到了一些问题。
这是我想链接到我的网页的“Schiphol PublicFlight API”。
但是我无法让 java 使用基于 JSON 的 API。
到目前为止,我已经尝试“隔离”越来越多的 JSON 代码,但我就是无法让它工作。为了让我更容易一些,我现在将 java servlet 代码从项目中分离出来。所以这是我现在的代码:
package nl.hva.ic103.johannes;
import java.io.FileReader;
import java.util.Iterator;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.*;
public class Main {
public static void main(String[] args) throws Exception {
JSONParser parser = new JSONParser();
String flightnumber = "HV6672";
HttpClient httpClient = HttpClients.createDefault();
HttpGet request = new HttpGet("https://api.schiphol.nl/public-flights/flights?app_id=61439ff8&app_key=b313373fd4122e93704874c69a59233d&flightname=" + flightnumber + "&sort=%2Bscheduletime");
request.addHeader("ResourceVersion", "v3");
HttpResponse response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(responseBody);
JSONObject jsonObject = (JSONObject) parser.parse(responseBody);
JSONObject jo = (JSONObject) jsonObject;
String id = (String) jo.get("id");
String lastName = (String) jo.get("flightName");
System.out.println(id);
System.out.println(lastName);
JSONArray ja = (JSONArray) jo.get("flights");
System.out.println(ja);
}
}
}
这是 API 给我的 JSON 格式:
{
"flights": [
{
"id": 125936439536285950,
"flightName": "HV6672",
"scheduleDate": "2018-12-26",
"flightDirection": "A",
"flightNumber": 6672,
"prefixIATA": "HV",
"prefixICAO": "TRA",
"scheduleTime": "01:00:00",
"serviceType": "J",
"mainFlight": "HV6672",
"codeshares": {
"codeshares": [
"KL2582"
]
},
"estimatedLandingTime": "2018-12-26T00:30:49.000+01:00",
"actualLandingTime": "2018-12-26T00:30:55.000+01:00",
"publicEstimatedOffBlockTime": null,
"actualOffBlockTime": null,
"publicFlightState": {
"flightStates": [
"LND",
"EXP"
]
},
"route": {
"destinations": [
"TFS"
]
},
"terminal": 1,
"gate": "D74",
"baggageClaim": {
"belts": [
"6"
]
},
"expectedTimeOnBelt": "2018-12-26T01:16:53.669+01:00",
"checkinAllocations": null,
"transferPositions": null,
"aircraftType": {
"iatamain": "73H",
"iatasub": "73H"
},
"aircraftRegistration": "PHHZX",
"airlineCode": 164,
"expectedTimeGateOpen": null,
"expectedTimeBoarding": null,
"expectedTimeGateClosing": null,
"schemaVersion": "3"
}
],
"schemaVersion": "3"
}
如何将“门”、“终端”和“飞机类型”等内容解析为我的 java 程序?我觉得我能从这些结果中得到的一切就像一个数据,不可能将数据分开。 有谁知道如何将这三个结果解析到我的 java 项目中? 有关 API 的更多信息列在他们的网站上: https://www.schiphol.nl/en/developer-center/page/our-flight-api-explored/
【问题讨论】:
-
我可能会考虑使用 GSON 库,它可以将 JSON 解析为 POJO