如何检查JSONArray元素是否为空

如何检查JSONArray元素是否为空

本文介绍了如何检查JSONArray元素是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚如何确定生活在json数组中的元素是否为null。要检查jsonObject本身是否为null,只需使用:

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();

但是当对象是一个数组并且我想检查该数组的其中一个元素是null,这不起作用:

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;

数组元素上也没有可用的isNull方法。如何检查jsonarray中的值是否为空?知道我从javascript传递一个null对象可能会有所帮助。也许null在java中以json格式从javascript传递时并不意味着同样的事情,但是我也尝试在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.

我发布了一些实际的源代码,以帮助更清楚。 jsonObject是jsonArray的一部分,对象有多个值,因为它是一个对象。

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


推荐答案

我猜json传递空值作为字符串,因此您不能将null检查为java元素。而是将null值视为字符串,以这种方式检查:

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.

这篇关于如何检查JSONArray元素是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 17:55