JSonException具有空值 [英] JSonException with null value

查看:113
本文介绍了JSonException具有空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解析JSon时遇到很多问题,其中一个值为空值.

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",
...
}

例如,如果"category_id"等于null,则解析器会出现异常.我该怎么解决?

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

推荐答案

在尝试从JSONObject获取值之前,您需要检查它是否具有键以及该值是否不是"null".

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

每次您尝试访问某个键时都添加此If语句:

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");      
}

这篇关于JSonException具有空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆