首页 > 解决方案 > 在 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 页面上,而不是在控制台上

标签: jsonspringspring-boot

解决方案


您的返回值似乎是一个有效的 Json 对象。如果您希望它更漂亮,以便您可以清楚地阅读它,然后将其传递给使该 json 更漂亮的应用程序。

如果你从 Postman 调用你的 API,它会给你一个漂亮的 Json 对象,它的格式会更好。这将是因为您已使用注释您的控制器,@RestController因此它将提供application/jsonPostman 将知道的响应,然后它将尝试使其更漂亮。

PS 它在 .html 页面上,而不是在控制台上

因此,您从浏览器中访问了您的 API。大多数浏览器不希望返回 Json 对象,因此它们不会让它变得漂亮。您也不能从您的服务中强制执行此操作。

只需从 Postman 中获取您的 API,它就会理解并使它变得漂亮。


推荐阅读