getJSON vs. optJSON
- Yes.
getJSONObject()
throws an exception when that object is not found.optJSONObject()
returns null. - Honestly there aren't really any advantages to one over the other, it's really a matter of personal preference.
- Only reason I can think of is for readability potentionally. For instance see how this code accomplishes the same thing
This option is a bit easier to read if you are doing a lot more when the object isn't present.
JSONObject object = jsonResponse.optJSONObject("object");if(object == null){ // handle not existing here}
This option is a bit easier if you are only throwing another exception or doing something else that's one line.
JSONObject object = null; try{ object = jsonResponse.getJSONObject("object");}catch(JSONException je){ // handle object not found here}