JSONException:尝试getString("XYZ")时没有XYZ的值

Shi*_*nsu 3 java android json exception-handling

我通过以下步骤在Android中进行JSON解析:

  1. 使用HttpPost对象从Web服务获取XML响应.
  2. 将此XML转换为JSON字符串,然后转换为JSON对象.

现在问题是有时XML响应具有空字符串或Null标记.

例如:

<data>
    <name>Martin Clark</name>
    <city>London</city>
    <country>XYZ</country> or <country />     <!-- Sometimes it will blank string like this if country is not available -->
    <age>27</age>
</data>
Run Code Online (Sandbox Code Playgroud)

解析风格:

jsonObject.getString("country"); // It is working perfect when xml is this : <country>XYZ<country/>

jsonObject.getString("country"); // It is giving Exception key is not found when xml is this : <country />
Run Code Online (Sandbox Code Playgroud)

我不明白为什么解析器没有给我空白XML对象的BLANK字符串.

通过深层次调试,我发现XML到JSON转换器不会产生对应于空白xml对象的对象.

请帮我.

JRo*_*ero 5

optString相反,使用Exception是昂贵且不必要的.

public String optString(String name)

在API级别1中添加返回按名称映射的值(如果存在),必要时强制它.如果不存在此类映射,则返回空字符串.

public String optString(String name,String fallback)

在API级别1中添加返回按名称映射的值(如果存在),必要时强制它.如果不存在这样的映射,则返回回退.

文档