Code :
String jsonStr = "{\"key\": null}";
JSONObject jsonObject = new JSONObject(jsonStr);
Map<String, Object> map = new ObjectMapper().readValue(jsonStr, Map.class);
if(jsonObject.get("random") == null) { // false
log.info("JSONObject");
}
if(map.get("random") == null) { // true
log.info("map");
}
Seems JSONObject is not able to handle the null values as a Map does, it's converting the null in jsonStr to "JSONObject.NULL" value.
Though JSONObject is internally using Map<String, Object>, but still this is a different way of null handling is present in the library. I don't know if there are other caveats in the library or not. We have caught this while dev testing. Seeing this behaviour we are thinking if we could use some other libraries than org.json.
Are there any better libraries than org.json.JSONObject, which matches it's efficiency and still doesn't have these caveats ?
I usually don't interact with JSON objects directly, I prefer to work "in Java" to use all of the language features and use JSON only as a form of serialization format to communicate with other applications (think about calling a REST endpoint from a language that does not have the "null" concept).
For JSONJava's JSONObject null handling I think it is a deliberate choice by the developers to implement the Null Object Pattern. If you look at the JSONObject javadoc you will see that it deserializes nulls as NULL objects such that
NULL.equals(null)is true. So to make your example work it is sufficient to use "equals()" method instead of "=="