Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getJSON vs. optJSON

Tags:

json

getjson

I was looking over the documentation for JSONObject when I noticed the two methods: getJSONObject(String key) and optJSONObject(String key). From the documentation, I figured they did nearly the same thing with one difference: If the key or value isn't found, then getJSONObject() throws a JSONException whereas optJSONObject() simply returns null.

  1. Are there any other differences between getJSONObject() and optJSONObject()?
  2. What are the advantages of get over opt and vice-versa?
  3. Are there specific situations where I would want to use one over the other or where the use of one is strongly discouraged/prohibited?
like image 255
Jason L Avatar asked Jul 03 '12 17:07

Jason L


3 Answers

A value in the JSON may be optional, so using optJSONObject is better because you just have to check if it is null or not and continue your function.

like image 144
StevenTB Avatar answered Nov 03 '22 03:11

StevenTB


optString returns the empty string ("") if the key you specify doesn't exist. getString throws a JSONException.

like image 26
Marzieh Bahri Avatar answered Nov 03 '22 05:11

Marzieh Bahri


  1. Yes. getJSONObject() throws an exception when that object is not found. optJSONObject() returns null.
  2. Honestly there aren't really any advantages to one over the other, it's really a matter of personal preference.
  3. 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
}
like image 37
hayden.mumm Avatar answered Nov 03 '22 04:11

hayden.mumm