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

时间:2014-04-29 12:36:36

标签: java json shell

此处字符串数据值来自shell脚本code.i需要以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();
         }

3 个答案:

答案 0 :(得分:2)

JSONArray arr = new JSONArray();

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

答案 1 :(得分:1)

我已使用此功能将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;
}

答案 2 :(得分:0)

您使用GSON是为了不必首先使用字符串......