首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用java循环json中的所有数据。

用java循环json中的所有数据。
EN

Stack Overflow用户
提问于 2018-07-19 19:02:56
回答 1查看 295关注 0票数 0

当我试图显示cmd元素的所有内容时,我对Java有一个问题。

代码语言:javascript
复制
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();


}

输出:

代码语言:javascript
复制
[{"cmd":"cmd-1"},{"cmd":"cmd-2"},{"cmd":"cmd-3"}]

我想使用foreach of cmd显示以下内容:

代码语言:javascript
复制
cmd-1
cmd-2
cmd-3
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-19 19:43:14

试试这段代码。希望能帮上忙。

代码语言:javascript
复制
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();


}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51430113

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档