在springboot中打印arraylist值

34gzjxbg  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(204)

我用RESTAPI中的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;

    }

}

最后一行“返回向量返回一个包含我分析的值的列表,并按如下方式返回:

但我希望这个更“漂亮”,我希望它是一个数组中的每一行,我如何才能实现这一点?
p、 它在.html页面上,而不是控制台上

8yoxcaq7

8yoxcaq71#

您的返回值似乎是一个有效的json对象。如果您希望它更漂亮,这样您就可以清楚地阅读它,然后将它传递给一个使json更漂亮的应用程序。
如果您从postman调用api,它将为您提供一个格式更好的json对象。这将是因为您已使用 @RestController 因此,它将提供一个 application/json 回复 Postman 会知道,然后它会尽量使它更漂亮。
p、 它在.html页面上,而不是控制台上
所以你从浏览器中点击你的api。大多数浏览器都不希望返回json对象,因此它们不会使它变得漂亮。你也不能强迫自己这么做。
只需点击postman的api,它就会理解它并使它变得漂亮。

相关问题