读书人

struts json序列化遇上replaceAll就出

发布时间: 2013-10-10 14:14:51 作者: rapoo

struts json序列化遇上replaceAll就出问题

是用struts 的json插件进行序列化
struts json序列化遇上replaceAll就出有关问题
?代码如下:

@Testpublic void test_json() throws JSONException {Map<String, String> map = new HashMap<String, String>();map.put("name", "whua\"ng");String result = JSONUtil.serialize(map);System.out.println(result);String source = "{\"result\":\"_jsonPlaceHolder\"}";String result2=source.replaceAll("\"" + "_jsonPlaceHolder" + "\"", result);System.out.println(result2);}

?运行结果如下:

{"name":"whua\"ng"}

{"result":{"name":"whua"ng"}}

?

是用json解析时报错,{"result":{"name":"whua"ng"}} 不是合法的json字符串。

经过反复看,发现whua\"ng中的斜杠没有了!!!!

问题出在replaceAll

?

解决方法如下

(添加).replaceAll("\\\\", "\\\\\\\\")

@Testpublic void test_json() throws JSONException {Map<String, String> map = new HashMap<String, String>();map.put("name", "whua\"ng");String result = JSONUtil.serialize(map);System.out.println(result);String source = "{\"result\":\"_jsonPlaceHolder\"}";String result2 = source.replaceAll("\"" + "_jsonPlaceHolder" + "\"",result.replaceAll("\\\\", "\\\\\\\\"));System.out.println(result2);}

?

?

读书人网 >JavaScript

热点推荐