JSON exception: no value for XYZ when trying to getString (“XYZ”)
I’m doing JSON parsing in Android with the following steps:
- Use the HttpPost object to get an XML response from a web service.
- Convert this XML to a JSON string and then to a JSON object.
The problem now is that sometimes XML responses have empty strings or empty tags.
For example:
<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>
Parsing style:
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 />
I don’t understand why the parser doesn’t give me a blank string for a blank XML object.
With deep debugging, I found that the XML to JSON converter does not generate an object corresponding to a blank XML object.
Please help me.
Solution
Using optString
instead, catching exceptions is costly and unnecessary.
public String optString (String name)
Added in API level 1 Returns the value mapped by name if it exists,
coercing it if necessary. Returns the empty string if no such mapping
exists.
public String optString (String name, String fallback)
Added in API level 1 Returns the value mapped by name if it exists,
coercing it if necessary. Returns fallback if no such mapping exists.