There are several ways to get value in Jsonobject, if you use the GetXxx () type method to get value, such as GetString ("key"). If key does not exist, these methods will throw an exception without exception. If an online environment throws an exception, it can make the error page appear, affecting the user experience, preferably using the Jsonobject optxxx method.
Take a look at the source code implementations of several getxxx () methods:
getString: If key does not exist, the GetString method throws an exception, as follows:
Public string getString (string key) { verifyisnull (); = get (key); if NULL ) { return o.tostring (); } Throw New Jsonexception ("jsonobject[" + jsonutils.quote (Key) + "] not found." ); }
getInt: If key does not exist, thegetInt method throws an exception, as follows:
Public int getInt (String key) { verifyisnull (); = get (key); if NULL ) { returninstanceof number? (number) O). Intvalue (): (int) getdouble (key); } Throw New Jsonexception ("jsonobject[" + jsonutils.quote (Key) + "] is not a number." ); }
getdouble: If key does not exist, thegetdouble method throws an exception, as follows:
Public Doublegetdouble (String key) {verifyisnull (); Object o=get (key); if(O! =NULL) { Try { returnOinstanceofNumber?(number) O). Doublevalue (): Double.parsedouble ((String) o); } Catch(Exception e) {Throw NewJsonexception ("jsonobject[" + jsonutils.quote (Key) + "] is not a number."); } } Throw NewJsonexception ("jsonobject[" + jsonutils.quote (Key) + "] is not a number."); }
Getboolean: If key does not exist, theGetboolean method throws an exception, as follows:
Public BooleanGetboolean (String key) {verifyisnull (); Object o=get (key); if(O! =NULL) { if(O.equals (boolean.false) | | (OinstanceofString && ((String) O). Equalsignorecase ("false"))) { return false; } Else if(O.equals (boolean.true) | | (OinstanceofString && ((String) O). Equalsignorecase ("true"))) { return true; } } Throw NewJsonexception ("jsonobject[" + jsonutils.quote (Key) + "] is not a Boolean."); }
Jsonobject has many optxxx methods, such as Optboolean,optstring,optint. Can look at these methods the implementation of the source code know that if Jsonobject has this property, then return this property, otherwise return a default value. The following example illustrates the underlying implementation of the Optstring method:
Public string optstring (string key) { verifyisnull (); return optstring (Key, ""); }
The above example indicates that if the key value does not exist, an empty string is returned.
Public string optstring (String key, string defaultvalue) { verifyisnull (); = opt (key); return null ? o.tostring (): defaultvalue; }
The above example indicates that if the key value does not exist, the default value of defaultvalueis returned.
JSON Learning Series (4) Use of the Optxxx method for-jsonstring objects