[psa] JSONObject.optString doesn't do what you think it does

Nick Alexander nalexander at mozilla.com
Thu May 22 17:28:18 PDT 2014

Hi m-f-d,

Just a friendly reminder that JSONObject.optString doesn't do what you 
think it does.  For terrible reasons documented at [1], if o = 
{'key':null}, then

JSONObject(o).optString("key") == "null"


JSONObject(o).optString("key", null) == "null"

That's right.  I discovered a few places in Fennec where NativeJSObject 
does a different thing [2], and then started to look at our use of 
optString, and it's not pretty.  Way too many uses to audit :(  So 
instead of trying to fix, I'm trying to educate instead.  Be careful 
when passing null from JS to Java!

We could try to make NativeJSObject do the right thing, but we have 
already gone quite far down the path of NativeJSObject is a drop-in 
replacement for JSONObject; I don't think we can go back.  And 
converting between the two conventions is as hard as auditing all 
current uses, amortized over time.


[1] http://stackoverflow.com/a/23377941

[2] https://bugzilla.mozilla.org/show_bug.cgi?id=1014965

More information about the mobile-firefox-dev mailing list