java - Why JsonNull in GSON? -


the docs jsonobject#get method returns null if no such member exists. that's not accurate; jsonnull object returned instead of null.

what idiom checking whether particular field exists in gson? wish avoid clunky style:

jsonelement = jsonobject.get("optional_field"); if (jsonelement != null && !jsonelement.isjsonnull()) {     s = jsonelement .getasstring(); } 

why did gson use jsonnull instead of null?

there answer what differences between null , jsonnull. in question above, i'm looking reasons why.

gson, presumably, wanted model difference between absence of value , presence of json value null in json. example, there's difference between these 2 json snippets

{} {"key":null} 

your application might consider them same, json format doesn't.

calling

jsonobject jsonobject = new jsonobject(); // {} jsonobject.get("key"); 

returns java value null because no member exists name.

calling

jsonobject jsonobject = new jsonobject(); jsonobject.add("key", jsonnull.instance /* or null */); // {"key":null} jsonobject.get("key"); 

returns instance of type jsonnull (the singleton referenced jsonnull.instance) because member exist name , value json null, represented jsonnull value.


Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -