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

是用struts 的json插件进行序列化

 代码如下:

@Test
	public 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("\\\\", "\\\\\\\\")

@Test
	public 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);
	}

 

 

你可能感兴趣的:(json,struts,replaceAll,斜杠转义,非法json)