Reputation: 263
I'm having lots of problems when parsing a JSon and one of it's values has null value.
{
"available_from" : "2012-11-05T00:00:00Z",
"available_to" : "2012-11-30T00:00:00Z",
"category_id" : 2,
"created_at" : "2012-11-05T14:53:39Z",
...
}
For example if "category_id" equals null I get an exception on my parser. What can I do to solve it?
Hope I've explained myself..
Upvotes: 2
Views: 3070
Reputation: 22469
Before trying to get a value from the JSONObject you need to check if it has the key and if the value is not "null".
Add this If statement every time you try to access a certain key:
JSONObject jsonObject = new JSONObject(str);
if(jsonObject.has("category_id")&&!jsonObject.isNull("category_id")){
String s = jsonObject.getString("category_id");
}
Upvotes: 4
Reputation: 28152
Considered using GSON? It really simplifies JSON parsing. Also if you are using regular jsonobjects the values may not be null. Read the documentation for further info.
Upvotes: 1