json - 在 SpringBoot 中打印 ArrayList 值
问题描述
我使用来自 Rest API 的 json 值创建了一个 ArrayList。
这是读取 Rest API 的代码:
@RestController
public class exemploclass {
@RequestMapping(value="/vectors")
//@Scheduled(fixedRate = 5000)
public ArrayList<StateVector> getStateVectors() throws Exception {
ArrayList<StateVector> vectors = new ArrayList<>();
String url = "https://opensky-network.org/api/states/all?lamin=41.1&lomin=6.1&lamax=43.1&lomax=8.1";
//String url = "https://opensky-network.org/api/states/all?lamin=45.8389&lomin=5.9962&lamax=47.8229&lomax=10.5226";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSONObject myResponse = new JSONObject(response.toString());
JSONArray states = myResponse.getJSONArray("states");
System.out.println("result after Reading JSON Response");
for (int i = 0; i < states.length(); i++) {
JSONArray jsonVector = states.getJSONArray(i);
String icao24 = jsonVector.optString(0);
String callsign = jsonVector.optString(1);
String origin_country = jsonVector.optString(2);
Boolean on_ground = jsonVector.optBoolean(8);
//System.out.println("icao24: " + icao24 + "| callsign: " + callsign + "| origin_country: " + origin_country + "| on_ground: " + on_ground);
//System.out.println("\n");
StateVector sv = new StateVector(icao24, callsign, origin_country, on_ground);
vectors.add(sv);
}
System.out.println("Size of data: " + vectors.size());
return vectors;
}
}
最后一行“返回向量;” 返回一个包含我解析的值的列表,并像这样返回它:
但我想要这个更“漂亮”,我希望它是每一行中的一个数组,我该如何实现呢?
PS 它在 .html 页面上,而不是在控制台上
解决方案
您的返回值似乎是一个有效的 Json 对象。如果您希望它更漂亮,以便您可以清楚地阅读它,然后将其传递给使该 json 更漂亮的应用程序。
如果你从 Postman 调用你的 API,它会给你一个漂亮的 Json 对象,它的格式会更好。这将是因为您已使用注释您的控制器,@RestController
因此它将提供application/json
Postman 将知道的响应,然后它将尝试使其更漂亮。
PS 它在 .html 页面上,而不是在控制台上
因此,您从浏览器中访问了您的 API。大多数浏览器不希望返回 Json 对象,因此它们不会让它变得漂亮。您也不能从您的服务中强制执行此操作。
只需从 Postman 中获取您的 API,它就会理解并使它变得漂亮。
推荐阅读
- security - Docker 容器通信
- firefox - 如何使用 fetch API 获取本地文件信息以获取 firefox 扩展
- dependency-injection - Ninject访问实例解析路径
- qt - 查找 Qt QML 文本元素的绘制 X 和 Y 位置(例如左上角)
- azure - 用于连接到 AzureRM 订阅上的 Azure 云服务实例的 Powershell 会话
- django - Python + Django + Celery 的发布速度非常低
- javascript - 来自 HTML 的“添加到阅读列表”
- c# - 在 asp.net mvc 的 Excel 工作表中导出表格视图
- android - Android - 在 http get 方法之外调用时,字符串返回空。
- python - Tkinker 文本输入投注