2019獨角獸企業重金招聘Python工程師標準>>>
? ? 同事在看到我寫的解析數據代碼后,告訴我optString比getString好用,optString不會拋異常,而getString會拋異常,自己是將信將疑,就說,回去后我查查資料。
? ? 在在stackoverflow上面看到一個解釋如下:
? ??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會在得不到你想要的值時候返回空字符串”“,而getString會拋出異常。至此,疑惑已經解除。
? ??