【问题标题】:Loop all data from json in java在java中循环来自json的所有数据
【发布时间】:2018-07-19 19:02:56
【问题描述】:

当我尝试显示来自cmd 元素的所有内容时,我遇到了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"}]

我想使用cmd 中的foreach 来显示以下内容:

cmd-1
cmd-2
cmd-3

【问题讨论】:

    标签: java json oop bufferedreader


    【解决方案1】:

    试试这个代码。希望对你有帮助。

    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();
    
    
    }
    

    【讨论】:

    • 不客气!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 2014-05-14
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多