搜尋此網誌

2016年12月24日 星期六

【Android】What is different optString() and getString() in JSONObject ?

ref:
http://stackoverflow.com/a/13790789

optString() 和 getString()差別?

The difference is that optString returns the empty string ("") if the key you specify doesn't exist. getString on the other hand throws a JSONException. Use getString if it's an error for the data to be missing, or optString if you're not sure if it will be there.
Edit: Full description from the documentation:
Get an optional string associated with a key. It returns an empty string if there is no such key. If the value is not a string and is not null, then it is converted to a string.

如果你指定的key不存在時,

optString()會回傳 ""



getString() 會跳出exception 因為 key為null。

沒有留言: