简体   繁体   English

Json中getString()和optString()之间的区别

[英]The difference between getString() and optString() in Json

JSON中getString()optString()什么区别?

As Diego mentions, it's a good idea to check the documentation (this link is now out of date - good thing we have the Wayback Machine! ) before posting a question here, but now that you have: 正如迭戈所提到的,检查文档是一个好主意(这个链接现在已经过时了 - 我们有Wayback Machine的好东西 ),然后在这里发布一个问题,但现在您已经:

The difference is that optString returns the empty string ( "" ) if the key you specify doesn't exist. 不同之处在于,如果您指定的密钥不存在, optString将返回空字符串( "" )。 getString on the other hand throws a JSONException . 另一方面, getString抛出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. 如果数据丢失则使用getString ,如果您不确定它是否存在则使用optString

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. 如果该值不是字符串且不为null,则将其转换为字符串。

If you want to avoid NullPointerException you better make use of optString() 如果你想避免NullPointerException你最好使用optString()

If you are fetching the data from JSON at any time, you might have null data for a particular Key value, at that time instead of implementing Null conditions, better make use of this optimized method optString("<keyname>") 如果您在任何时候从JSON获取数据,那么您可能拥有特定Key值的null数据,而不是实现Null条件,更好地利用此优化方法optString("<keyname>")

public java.lang.String optString(int index) Get the optional string value associated with an index. public java.lang.String optString(int index)获取与索引关联的可选字符串值。 It returns an empty string if there is no value at that index. 如果该索引没有值,则返回空字符串。 If the value is not a string and is not null, then it is coverted to a string. 如果该值不是字符串且不为null,则将其转换为字符串。 Parameters: index - The index must be between 0 and length() - 1. Returns: A String value. 参数:index - 索引必须介于0和length()之间 - 1.返回:字符串值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM