getJSON vs. optJSON

Jason L picture Jason L · Jul 3, 2012 · Viewed 14.3k times · Source

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?

Answer

StevenTB picture StevenTB · Apr 18, 2013

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.