There are several ways to get value in Jsonobject, and if key does not exist, none of these methods will throw an exception. If an online environment throws an exception, it can make the error page appear, affecting the user experience, preferably using the Optxxx method.
1 Publicstring getString (string key)2 {3 verifyisnull ();4Object o =get (key);5 if(O! =NULL)6 {7 returno.tostring ();8 }9 Throw NewJsonexception ("jsonobject[" + jsonutils.quote (Key) + "] not found.");Ten}
View Code
The Getint method throws an exception, as follows:
1 Public intgetInt (String key)2 {3 verifyisnull ();4Object o =get (key);5 if(O! =NULL)6 {7 returnOinstanceofNumber? (number) O). Intvalue (): (int) getdouble (key);8 }9 Throw NewJsonexception ("jsonobject[" + jsonutils.quote (Key) + "] is not a number.");Ten}
View Code
The GetDouble method throws an exception, as follows:
1 Public Doublegetdouble (String key)2 {3 verifyisnull ();4Object o =get (key);5 if(O! =NULL)6 {7 Try8 {9 returnOinstanceofNumber?(number) O). Doublevalue (): Double.parsedouble ((String) o);Ten } One Catch(Exception e) A { - Throw NewJsonexception ("jsonobject[" + jsonutils.quote (Key) + "] is not a number."); - } the } - Throw NewJsonexception ("jsonobject[" + jsonutils.quote (Key) + "] is not a number."); - -}
View Code
The Getboolean method throws an exception, as follows:
1 Public BooleanGetboolean (String key)2 {3 verifyisnull ();4Object o =get (key);5 if(O! =NULL)6 {7 if(O.equals (boolean.false) | | (OinstanceofString && ((String) O). Equalsignorecase ("false")))8 {9 return false;Ten } One Else if(O.equals (boolean.true) | | (OinstanceofString && ((String) O). Equalsignorecase ("true"))) A { - return true; - } the } - Throw NewJsonexception ("jsonobject[" + jsonutils.quote (Key) + "] is not a Boolean."); -}
View Code
Jsonobject has many optxxx methods, such as Optboolean,optstring,optint. They mean that if Jsonobject has this property, this property is returned, otherwise a default value is returned. The following is an example of the underlying implementation of the Optstring method: Jsonobject has many optxxx methods, such as Optboolean,optstring,optint. They mean that if Jsonobject has this property, this property is returned, otherwise a default value is returned. The following example illustrates the underlying implementation of the Optstring method:
1 Public string optstring (string key) 2 {3 verifyisnull (); 4 return optstring (Key, ""); 5 }
View Code
1 Public string optstring (String key, string defaultvalue) 2 {3 verifyisnull (); 4 Object o = opt (key); 5 return null ? o.tostring (): defaultvalue; 6 }
View Code
JSON tutorial Series (4) Use of the-optxxx method