java - 在java中循环来自json的所有数据
问题描述
当我尝试显示cmd
's 元素中的所有内容时,我遇到了 Java 问题。所以这是我的代码:
public static void main(String[] args) throws Exception {
// Json Stream Reader
String jsonS = "";
// Connect to web api
URL url = new URL("http://b50172e8.ngrok.io/api/plugin/521100d075c1284b944841394e157744");
// Make Connection
URLConnection conn = url.openConnection();
conn.setRequestProperty("Accept","*/*");
conn.connect();
// Stream reader
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while((inputLine = in.readLine()) != null) {
jsonS+=inputLine;
}
// Read json response
Gson gson = new Gson();
// Json Object
JsonObject jsonObject= gson.fromJson(jsonS, JsonObject.class);
JsonElement data = jsonObject.get("data");
System.out.println(data);
// Close connection
in.close();
}
输出:
[{"cmd":"cmd-1"},{"cmd":"cmd-2"},{"cmd":"cmd-3"}]
我想使用foreach
来cmd
显示以下内容:
cmd-1
cmd-2
cmd-3
解决方案
试试这个代码。我希望它有所帮助。
public static void main(String[] args) throws Exception {
// Json Stream Reader
String jsonS = "";
// Connect to web api
URL url = new URL("http://b50172e8.ngrok.io/api/plugin/521100d075c1284b944841394e157744");
// Make Connection
URLConnection conn = url.openConnection();
conn.setRequestProperty("Accept","*/*");
conn.connect();
// Stream reader
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while((inputLine = in.readLine()) != null) {
jsonS+=inputLine;
}
// Read json response
Gson gson = new Gson();
// Json Object
JsonObject jsonObject= gson.fromJson(jsonS, JsonObject.class);
JsonArray data = jsonObject.getAsJsonArray("data");
//here data is JsonArray and it contains everithing: [{"cmd":"cmd-1"},{"cmd":"cmd-1"},{"cmd":"cmd-1"}]
data.forEach(el -> {
//Get Json object which has key and value -> {"cmd":"cmd-1"}
JsonObject jo = el.getAsJsonObject();
//get the value as Json element -> "cmd-1"
JsonElement je = jo.get("cmd");
//Then make the json element string
String value = je.getAsString();
System.out.println(value);
});
//System.out.println(data);
// Close connection
in.close();
}
推荐阅读
- php - 无法运行用于创建新表的脚本
- apache-spark - org/apache/spark/Hbase-Spark 上的日志记录问题
- blockchain - 如何在我的私有网络中设置 Zcash?
- java - Appium Java sendText(); 无法发送字母“a”和“b”
- php - 谷歌地图地理定位不征求许可
- powershell - Windows10 Powershell - 闹钟、世界时钟、计时器、秒表?
- excel-2010 - 获取 Excel 中的当前列号(非编程方式)
- python - 我怎样才能拉数字之间
- asp.net - 使用子字符串从字符串中提取值
- oracle - 设置 TERMOUT OFF 时如何在不达到缓冲区限制的情况下 SPOOL 输出不起作用