简体   繁体   English

如何将 ArrayList 转换为 JSON Object 以便能够在 ZD52387880E1EA921387A 中迭代它?

[英]How can I convert an ArrayList to JSON Object to be able to iterate through it in Java?

I am trying to loop through a json object I pulled through the web but I can't seem to convert it from a string to a jsonarray or jsonobject.我试图循环通过 json object 我通过 web 但我似乎无法将其从字符串转换为 jsonarray 或 jsonobject。 I want to be able to use a for loop to iterate through it and then conditionally output names based on some values.我希望能够使用 for 循环遍历它,然后根据某些值有条件地使用 output 名称。

This is a simple java program to demonstrate pulling json data from a web api and then looping through it.这是一个简单的 java 程序,用于演示从 web Z8A5DA52ED1264217D359E70C 中提取 json 数据然后循环遍历它。

Here's the code:这是代码:

  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;
    }
 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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM