getJSON vs. optJSON

独自空忆成欢 提交于 2019-11-30 00:24:02

问题


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?

回答1:


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.




回答2:


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




回答3:


I'm using optJSONObject to my json file with key "sentences" and it return null but the correct result might JSONArray or String.

{
"sentences":[
  {
     "trans":"làm",
     "orig":"do",
     "translit":"",
     "src_translit":""
  }
]
}


来源:https://stackoverflow.com/questions/11316152/getjson-vs-optjson

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!