java数组里的元素为空,如何检查JSONArray元素是否为空

I can't figure out how to determine is an element that lives inside a json array is null. To check if the jsonObject itself is null, you simply use:

jsonObject.isNullObject();

But when the object is an array and I want to check if one of the elements of that array is null, this does not work:

jsonArray.get(i).get("valueThatIsNull") == null;

There is also no isNull method available on elements of an array. How do I check if values inside a jsonarray are null? It might help to know that I am passing over a null object from javascript. Maybe null does not mean the same thing in java when it is passed from javascript in json format, but I have also tried putting parentheses around the null and it still does not work.

I am posting some actual source code to help make this clearer. The jsonObject is a part of the jsonArray and the object has multiple values because it iself is an object.

JSONObject mapItem = jsonArray.getJSONObject(i);

int id = mapItem.has("id") ? mapItem.getInt("id") : -1;

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

java.util.Date date = null;

Date sqlDate = null;

if(mapItem.has("date")) {

String dateStr = mapItem.getString("date");

if(!dateStr.equals("null")) {

date = dateFormat.parse(mapItem.getString("date").substring(0, 10)); //Convert javascript date string to java.

sqlDate = new Date(date.getTime());

}

解决方案

I guess json passes null values as strings, so you can't check null as a java element. Instead treat the null value as a string as check this way:

if(!mapItem.getString("date").equals("null")) {

//Value is not null

}

I have updated the code snippet in the original question to a working version.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值