Posted In: JSON

Are escaping special characters in JSON string required?

 

Following tests with various libraries confirms that JSON library will handle special characters and there is no need to use StringEscapeUtilities.escapeHtml, StringEscapeUtilities.escapeXml or java.net.URLEncoder

 

1. Example will use following Test data

private String testData1() {
	String json = "{"
			+ " \"specialchars\": \"~!@#$%^&*()_+{}:<>?`-=[];',./\"}";
	return json;
}

 

2. Using GSON

@Test
public void gson1() {
	com.google.gson.JsonObject object = new JsonParser()
			.parse(testData1()).getAsJsonObject();
	assertEquals(object.get("specialchars").getAsString(),
			"~!@#$%^&*()_+{}:<>?`-=[];',./");
}

 

3. Using Jackson 2X

@Test
public void jackson2x1() throws Exception {
	ObjectMapper objectMapper = new ObjectMapper();
	Reader reader = new StringReader(testData1());
	ObjectNode object = objectMapper.readValue(reader,
			ObjectNode.class);
	assertEquals(object.get("specialchars").asText(),
			"~!@#$%^&*()_+{}:<>?`-=[];',./");
}

 

4. Using Jackson 1X

@Test
public void jackson1x1() throws Exception {
	org.codehaus.jackson.map.ObjectMapper objectMapper = 
			new org.codehaus.jackson.map.ObjectMapper();
	Reader reader = new StringReader(testData1());
	org.codehaus.jackson.node.ObjectNode object = objectMapper
			.readValue(reader,
					org.codehaus.jackson.node.ObjectNode.class);
	assertEquals(object.get("specialchars").asText(),
			"~!@#$%^&*()_+{}:<>?`-=[];',./");
}

 

5. Using com.jsoniter.output.JsonStream from json iterator library

@Test
public void jsonIterator1() throws Exception {
	Any object = JsonIterator.deserialize(testData1(),
			Any.class);
	assertEquals(object.get("specialchars").toString(),
			"~!@#$%^&*()_+{}:<>?`-=[];',./");
}

 

6. Using net.sf.json.JSONArrayfrom net.sf.json-lib library

@Test
public void netsfjsonlib1() throws Exception {
	JSONObject object = JSONObject.fromObject(testData1());
	assertEquals(object.get("specialchars").toString(),
			"~!@#$%^&*()_+{}:<>?`-=[];',./");
}

 

7. Output

All tests run successfully

 

Tags: , , , , ,

by , on February 22nd, 2017

  • Categories