如何检查 JSONArray 元素是否为空 [英] How to check if JSONArray Element is null
问题描述
我不知道如何确定位于 json 数组中的元素是否为空.要检查 jsonObject 本身是否为空,您只需使用:
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;
数组元素也没有可用的 isNull 方法.如何检查 jsonarray 中的值是否为空?知道我从 javascript 传递了一个空对象可能会有所帮助.当 null 以 json 格式从 javascript 传递时,也许 null 在 java 中并不意味着同样的事情,但我也尝试在 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 值作为字符串传递,因此您不能将 null 作为 java 元素进行检查.而是将空值视为字符串,以这种方式检查:
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 元素是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!