1. 程式人生 > >Json和Python通過Json互動中出現轉義的問題

Json和Python通過Json互動中出現轉義的問題

後端springboot當把

JSONObject jObject1=new JSONObject();
jObject1.put("operate_name", "input_data");
jObject1.put("excelAllData", excelAllData);
jObject1.put("excelHeadList", excelHeadList);
jObject1.put("proj_name", "測試");
String strJson= jObject1.toJSONString();   -------2》
System.out.println(strJson);
列印的結果為:
{"operate_name":"input_data","excelHeadList":["ID","TOOL_ID","210X1","210X2","210X3"],"excelAllData":[["ID001","N","100.0","800.0","0.27"],["ID002","M","200.0","700.0","0.22"],["ID003","L","300.0","600.0","0.24"],["ID004","M","400.0","500.0","0.22"],["ID005","M","500.0","400.0","0.23"],["ID006","M","600.0","300.0","0.22"],["ID007","N","700.0","200.0","0.27"],["ID010","N","800.0","100.0","0.27"]],"proj_name":"多元分析測試"}
和Python互動的程式碼
String[] arguments = new String[]{"python", "D:\\work\\Python_code\\py_java_io.py", strJson};
try {
    Process process = Runtime.getRuntime().exec(arguments);
    InputStreamReader isr = new InputStreamReader(process.getInputStream(), "GBK");
    BufferedReader in = new BufferedReader(isr);
    String line = null;
    while ((line = in.readLine()) != null) {
        System.out.println(line);
    };
    in.close();
    int re = process.waitFor();    ------1》如果是1表示呼叫python錯誤,為0表示正確
System.out.println(re); System.out.println("標記錯誤的地方"); String strErr = process.getErrorStream().toString(); System.out.println(strErr); } catch (Exception ex) { ex.printStackTrace(); }

當把上面列印的結果放入後總是列印1,表示呼叫python錯誤,

後來百度:在-------2》地方加入

strJson=  strJson.replaceAll("\"", "\\\\\"" );
System.out.println(strJson);

列印的結果為:

{\"operate_name\":\"input_data\",\"excelHeadList\":[\"ID\",\"TOOL_ID\",\"210X1\",\"210X2\",\"210X3\"],\"excelAllData\":[[\"ID001\",\"N\",\"100.0\",\"800.0\",\"0.27\"],[\"ID002\",\"M\",\"200.0\",\"700.0\",\"0.22\"],[\"ID003\",\"L\",\"300.0\",\"600.0\",\"0.24\"],[\"ID004\",\"M\",\"400.0\",\"500.0\",\"0.22\"],[\"ID005\",\"M\",\"500.0\",\"400.0\",\"0.23\"],[\"ID006\",\"M\",\"600.0\",\"300.0\",\"0.22\"],[\"ID007\",\"N\",\"700.0\",\"200.0\",\"0.27\"],[\"ID010\",\"N\",\"800.0\",\"100.0\",\"0.27\"]],\"proj_name\":\"多元分析測試\"}
 

通過轉義後再通過和Python互動正確

 

 

今天在專案中使用java中replaceAll方法將字串中的反斜槓("\")替換成空字串(""),結果出現如下的異常:

1 java.util.regex.PatternSyntaxException: Unexpected internal error near index 1 \^

  上網找了一下錯誤的原因:在regex中"\\"表示一個"\",在java中一個"\"也要用"\\"表示。這樣,前一個"\\"代表regex中的"\",後一個"\\"代表java中的"\"。所以要想使用replaceAll方法將字串中的反斜槓("\")替換成空字串(""),則需要這樣寫:str.replaceAll("\\\\","");

  寫一段測試程式碼演示上面出現的異常:

1 String s="C:\盤";
2 s.replaceAll("\\","");

  使用上面的程式碼會導致

1 java.util.regex.PatternSyntaxException: Unexpected internal error near index 1 \^

  要想將"C:\盤"中的"\"替換成空字串,正確的寫法是:

1 s.replaceAll("\\\\","");

  這樣就可以正常替換了。