JSON 格式:
{\"日志\":\"2017-12-02 12:03:19,\\\\\\\"elapsedRealtime\\\\\\\":\\\\\\\"1075259399471\\\\\\\",\\\\\\\"source0Id\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"cheme\\\\\\\":\\\\\\\"false\\\\\\\",\\\\\\\"sourceFromUri\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"sourceTime\\\\\\\":\\\\\\\"-1\\\\\\\",\\\\\\"supportCache\\\":\\\"false\\\",\\\"suppode\\\":\\\"true\\\",\\\"paiType\\\":\\\"ode\\\",\\\"protersion\\\\\\\":\\\\\\\"5.5.1\\\\\\\"}
主要是串行序列化之后,转译成对象而后又转化为JSONOBject主要是因为Array->Obecjt 转义多次导致的。
解决办法就是使用StringEscapeUtils的处理进行转义。
import org.apache.commons.lang.StringEscapeUtils; //主要是解决转义符太多斜杆个问题\\\\\\\",\\\\\\\" datasJson=StringEscapeUtils.unescapeJavaScript(datasJson); sout(datasJson);
第三方优秀的处理JAR:
import org.apache.commons.lang.StringEscapeUtils;
发生场景主要是发生在接口对接的时候,接收对象处理,以及对象发送。
主要得maven依赖配置:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency>
教训总结:
在数据库之前使用这个字符串工具进行转义,虽然断点显示,转换正常,可是落库之后,Mysql会对JSON字符串里面的网址或者存储进行转义,导致会添加一个\,所以最优化的方案就是在读取之后进行转义,这样一劳永逸。后者前台页面进行转义,比较麻烦。
前端的React其实也可以达到这个效果,主要是使用replace()
替换掉里面的斜杠。
try{ let e1 = e.replace(/\\\\/g,"\\"); e1 = e1.replace(/\\\\/g,"\\"); e1 = this.replaceAll(e1, '&', ''); e1 = this.replaceAll(e1, '"', '"'); e1 = this.replaceAll(e1, 'quot;', '"'); e1 = this.replaceAll(e1, 'lt;', '<'); e1 = this.replaceAll(e1, 'agt;', '>'); return content; } catch (e){ console.log(e); return e1 ;