拆分Json输出并将其分配给两个不同的对象

时间:2018-10-01 12:13:03

标签: java json shell

这是我的Java:它将在何处运行shell脚本并获取输出:

public static void main(String[] args) throws IOException, JSONException {

    ProcessBuilder pb = new ProcessBuilder("/test.sh");
    Process p = pb.start();
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = null;

    while ((line = reader.readLine()) != null)
    {
        JSONObject jSONObject = new JSONObject(line);
        System.out.println("Parsed JSON : " + jSONObject);

    }
}

}

这是我的输出:

Parsed JSON : {"network-metrics":{"interfaces":["eth0",{"status":{"TX":{"carrier":"0","bytes":"54835108","dropped":"0","overruns":"0","packets":"356928","errors":"0"},"RX":{"bytes":"739960761","dropped":"68","overruns":"0","packets":"766292","errors":"0","frame":"0"}}},"lo",{"status":{"TX":{"carrier":"0","bytes":"185357","dropped":"0","overruns":"0","packets":"967","errors":"0"},"RX":{"bytes":"185357","dropped":"0","overruns":"0","packets":"967","errors":"0","frame":"0"}}},"mlan0",{"status":{"TX":{"carrier":"0","bytes":"30056","dropped":"0","overruns":"0","packets":"542","errors":"0"},"RX":{"bytes":"275867466","dropped":"0","overruns":"7229","packets":"272573","errors":"272573","frame":"0"}}}]}}
Parsed JSON : {"os-metrics":{"NumberOfProcess":"242","Up Time":"8 hours, 7 minutes","Disk Usage":"33%","CPU Usage":"5.77916%"}}

所以在这里。如何将网络指标和操作系统指标分配给两个不同的对象

1 个答案:

答案 0 :(得分:0)

尝试一下。

public static void main(String[] args) throws IOException, JSONException {

    ProcessBuilder pb = new ProcessBuilder("/test.sh");
    Process p = pb.start();
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = null;

    // Initialize 2 JSON Objects
    JSONObject networkMetrics = new JSONObject();
    JSONObject osMetrics = new JSONObject();

    while ((line = reader.readLine()) != null)
    {
        JSONObject jSONObject = new JSONObject(line);

        System.out.println("Parsed JSON : " + jSONObject);

        // Get the JSON Objects if they exist
        if (jSONObject.has("network-metrics")) {
             networkMetrics = jSONObject.getJSONObject("network-metrics");
             System.out.println("Network Metrics JSON : " + networkMetrics);
        }
        if (jSONObject.has("os-metrics")) {
             osMetrics = jSONObject.getJSONObject("os-metrics");
             System.out.println("OS Metrics JSON : " + osMetrics);
        }   
    }
}