繁体   English   中英

如何将字符串数据转换为json?

[英]how to convert string data into json?

这里的字符串数据值来自shell脚本代码。我需要以json格式显示此结果值

Runtime rt = Runtime.getRuntime();
             Process pr = rt.exec(new String[]{"/home/admin/institutestatus.sh"});

         BufferedReader input = new BufferedReader(new  InputStreamReader(pr.getInputStream()));
             String line = "";

             while ((line = input.readLine()) != null) {

                 Gson gson =new Gson();
                 System.out.println(gson.toJson(line));
             }
         } catch (Exception e) {
             System.out.println(e.toString());
             e.printStackTrace();
         }
JSONArray arr = new JSONArray();

 while ((line = input.readLine()) != null) {
    JSONObject obj = new JSONObject();
    obj.put("value",line);
    arr.add(obj);
}

我已使用此函数将InputStream转换为String并将转换为JSONObject

public static String load(final InputStream in) {
    String data = "";
    try {
        InputStreamReader is = new InputStreamReader(in, Charset.forName("UTF-8"));
        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader(is);
        String read = br.readLine();
        while (read != null) {
            sb.append(read);
            read = br.readLine();
        }
        data = sb.toString();
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
    return data;
}

您使用GSON是为了不必首先使用Strings ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM