Came across a recent issue where user submitted string value 'null' is being stored into the data base as '"null"'. Basically double quotes are being added at the start and end of the String.
Investigation revealed that JSON-lib doesn't seem to handle the 'null' string value correctly. This is exhibited by the following test methods.
@Test
public void shouldHandleNullStringInJsonFormattedString() {
String jsonTest = "[\"null\",\"aValue\"]";
assertTrue(jsonTest.contains("\"null\""));
assertFalse(jsonTest.contains("\"\\\"null\\\"\""));
String convertedBack = JSONSerializer.toJSON(jsonTest).toString();
// fails at below line
assertFalse(convertedBack.contains("\"\\\"null\\\"\""));
}
@Test
public void shouldHandleNullStringLiteral() {
JSONArray jsonArray1 = JSONArray.fromObject(Arrays.asList(null,"b"));
JSONArray jsonArray2 = JSONArray.fromObject(Arrays.asList(JSONNull.getInstance(),"b"));
JSONArray jsonArray3 = JSONArray.fromObject(Arrays.asList("null","b"));
assertEquals("[null,\"b\"]", jsonArray1.toString());
assertEquals("[null,\"b\"]", jsonArray2.toString());
//fails at below line
assertEquals("[\"null\",\"b\"]", jsonArray3.toString());
}
basically when browser sends ["null", "aValue"] to server, JSON-lib changes it to ["\"null\"", "aValue"]. Also from the server side we are unable to construct a JSON formatted String like ["null", "b"] using JSONArray. JSON-lib does not seem to handle these two basic scenarios properly.
Have emailed to the mailing list and contact email addressed on their site but no response yet. It seems like someone has previously posted about this issue on
http://sourceforge.net/p/json-lib/discussion/587134/thread/faf83e9a/
But no response for that either.
Any body has any suggestions/fixes for this issue ?
We are using the latest version of json-lib i.e 2.4
Update
Looking at the source code of json lib net.sf.json.util.JSONUtils.mayBeJSON method is a bit weird.
public static boolean mayBeJSON( String string ) {
return string != null
&& ("null".equals( string )
|| (string.startsWith( "[" ) && string.endsWith( "]" )) || (string.startsWith( "{" ) && string.endsWith( "}" )));
}
Seems like any literal String value of 'null' is considered JSON ??