我试图循环遍历一个从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;
}
1条答案
按热度按时间vhmi4jdf1#