带有空字段的JSON对象

时间:2014-03-29 18:29:05

标签: java android json foursquare

我从foursquare得到一个场地列表,我需要每个场地的名称,地址和城市。这里我的问题是如果地址或城市为空,它会给出错误并说“JSON例外:没有地址值”。我尝试了不同的方法来解决它,但无法解决问题。我希望你能帮助我。谢谢。

JSONObject b = venues.getJSONObject(i);
JSONObject location = b.getJSONObject("location");

String name = "";
String address = "";
String city = "";

if ("".equals(b.get("name"))) {
    //  Toast.makeText(Activity2.this,"Name of Place: " +name+ " Location: "+country, Toast.LENGTH_SHORT).show();
    name = "No place ";
} else {
    name = b.getString("name");
}

if ("".equals(location.getString("address"))) {
    address = "No address";
} else {
    address = location.getString("address");
}

if ("".equals(location.getString("city"))) {
    city = "No city";
} else {
    city = location.getString("city");
}

name = "Name of the place: " + name; 
// + " Address: "+ address + "  City: " + city;
list.add(name);

2 个答案:

答案 0 :(得分:3)

您可能需要在调用getString之前调用has()方法以避免异常。但是有一个更简单的方法 - 只需使用optString而不是getString,它将返回"后退"如果值不存在,则为字符串。

String name = location.optString("name", "No Place");
String address = location.optString("address", "No Address");
String city = location.optString("city", "No City");

答案 1 :(得分:2)

.Json对象“location”不包含address值,您必须添加另一个评估。

location.getString("address") = null;

例如:

if ((location.getString("address") = null) || "".equals(location.getString("address"))) {
    address = "No address";
} else {
    address = location.getString("address");
}

或使用optString()方法

查看selbie的解决方案
String address = location.optString("address", ""); //where "" is a default value.