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.
简而言之:optString对应的key中值不存在返回空字符串”“或者是你指定的默认值,而getString会抛出JSONException异常。