【问题标题】:How can I convert an ArrayList to JSON Object to be able to iterate through it in Java?如何将 ArrayList 转换为 JSON 对象以便能够在 Java 中遍历它?
【发布时间】:2021-02-24 12:39:04
【问题描述】:

我正在尝试遍历从网络中提取的 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;
    }

【问题讨论】:

  • 您已经将用户名放入了 ArrayList。为什么不遍历该列表?为什么要将 List 转换为 JsonArray?
  • 我希望能够将数据从 json 提取到变量中,以便我可以使用它有条件地将名称输出到用户名。处理json数据时使用json数组不是更方便吗?
  • 我假设因为您的列表被称为usernames,所以它将是一个包含用户名的列表。如果您只是读取单个 JSON 字符串,那么将每一行保存为 ArrayList 中的元素可能是您出错的地方。只需将 JSON 数据保存/附加到单个字符串中,然后尝试将该字符串解析为 JSON。
  • 我现在将数据作为字符串保存在 responseContent 中,但是如何将字符串解析为 JSON?
  • 您能否提供您得到的响应字符串?

标签: java json gson


【解决方案1】:
 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);
    }

【讨论】:

    猜你喜欢
    • 2017-09-19
    • 2022-01-15
    • 2019-04-19
    • 2014-08-28
    • 1970-01-01
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多