gson 如何将ArrayList转换为JSON对象,以便能够在Java中对其进行迭代?

jv2fixgn  于 2022-11-06  发布在  Java
关注(0)|答案(1)|浏览(170)

我试图循环遍历一个从web上拉来的json对象,但是我似乎无法将其从字符串转换为jsonarray或jsonobject。我希望能够使用for循环来遍历它,然后根据一些值有条件地输出名称。
这是一个简单的java程序,演示如何从web api中提取json数据,然后在其中循环。
下面是代码:

public static List<String> getUsernames(int threshold) throws IOException {
        List<String> usernames = new ArrayList<>();

        BufferedReader reader;
        String line;
        StringBuffer responseContent = new StringBuffer();
        try {
            URL url = new URL("url to json api");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            //Request method
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            int status = connection.getResponseCode();
            System.out.println(status);

            if (status > 299) {
                reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
                while ((line = reader.readLine()) != null) {
                    responseContent.append(line);
                }
                reader.close();
            } else {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                while ((line = reader.readLine()) != null) {
                    usernames.add(line);
                }

//                String json = new Gson().toJson(usernames);
//
//                JSONArray jsonarray = new JSONArray(json);
//                System.out.println(json);

                Gson gson = new Gson();

                reader.close();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return usernames;
    }
vhmi4jdf

vhmi4jdf1#

List<String> usernames = new ArrayList<>();
    usernames.add("Hibernate");
    usernames.add("spring");

    JSONArray jsonStr = new JSONArray().put(usernames);

    for (Object values: jsonStr) {
        System.out.println(values);
    }

相关问题