2014-03-29 32 views
2

我收到來自foursquare的場地列表,我需要每個場地的名稱,地址和城市。在這裏,我的問題是如果地址或城市是空的,它會給出錯誤,並說「JSON異常:地址沒有值」。我嘗試了不同的方法來修復它,但無法解決問題。我希望你能幫助我。謝謝。帶空字段的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); 

回答

3

您可能需要調用有()方法調用的getString避免之前例外。但還有一種更簡單的方法 - 只需使用optString而不是getString,如果該值不存在,將返回「fallback」字符串。

​​
+0

感謝隊友它是好的,知道這個optString功能 –

+0

+1,對我來說非常有用:) – Jorgesys

2

的以.json對象 「location」 doesn't包含address值,你得再添評價。

location.getString("address") = null; 

例如:

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

或看到selbie's解決方案使用optString()方法

String address = location.optString("address", ""); //where "" is a default value. 
+0

謝謝這個工作太 –