【问题标题】:JSONException: no value for XYZ when trying to getString("XYZ")JSONException:尝试 getString("XYZ") 时 XYZ 没有值
【发布时间】:2014-05-11 07:33:30
【问题描述】:

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

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

现在的问题是有时 XML 响应有空字符串或空标签。

例如:

<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>

解析风格:

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 />

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

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

请帮帮我。

【问题讨论】:

  • 为什么将xml转换成json可以自己解析xml

标签: java android json exception-handling


【解决方案1】:

改用optString,捕获异常是昂贵且不必要的。

公共字符串 optString(字符串名称)

在 API 级别 1 中添加 如果存在,则返回按名称映射的值, 必要时强制执行。如果没有这样的映射,则返回空字符串 存在。

public String optString(字符串名称,字符串回退)

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

Documentation

【讨论】:

    【解决方案2】:

    您可以使用逻辑解决方案来解决您的问题。

    试试这个。

    public static String getStringFromJSON(JSONObject json, String key){
    
    
        String value = ""; // Blank string by default.  
    
        try {       
    
            String value = json.getString(key);
    
    
            return value;
        }
            catch(JSONException exp){
    
            exp.getMessage();
    
        }
    
        return value;  // this wil return BLANk string if object is not prasent.
    
    }
    

    你可以用这个方法从 json 对象中获取字符串,

    【讨论】:

      猜你喜欢
      • 2010-09-08
      • 2021-04-05
      • 2015-11-06
      • 2015-12-28
      • 1970-01-01
      • 2013-08-27
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多