问题
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.
- Are there any other differences between
getJSONObject()andoptJSONObject()? - What are the advantages of
getoveroptand vice-versa? - 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