[英]How can I convert an ArrayList to JSON Object to be able to iterate through it in Java?
我试图循环通过 json object 我通过 web 但我似乎无法将其从字符串转换为 jsonarray 或 jsonobject。 我希望能够使用 for 循环遍历它,然后根据某些值有条件地使用 output 名称。
这是一个简单的 java 程序,用于演示从 web Z8A5DA52ED1264217D359E70C 中提取 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;
}
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.