后端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("\\\\","");

  这样就可以正常替换了。

 

 

 

 

GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:1 个月前 )
960b763e 4 个月前
8c391e04 6 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐