我想检查我的数据是否有空值。 JSON格式的数据如下:
"{
"totalAmount" : 20000,
"items" : [
{
"id" : "9fd91eaf-2b9a-4bae-9692-4222f85e868",
"name" : "X hotel",
"itemType" : 0,
"orderCount" : 2,
"amount" : 5000
},
{
"id" : "9fd91eaf-2b9a-4bae-9692-4222f85e869",
"name": "Special Dinner",
"itemType" : 1,
"orderCount" : 1,
"amount" : 10000
}
]
}"
这是我的检查器逻辑。
class NullCheck {
public checkNull (Itinerary itinerary)
Object nu = null;
if (itinerary == null) {
return true;
} else if (itinerary.getTotalAmount() == null || itinerary.getItems() == null) {
return true;
} else if (itinerary.getItems().contains(null)) {
return true;
} else if (itinerary.getItems().stream().flatMap //
(item -> Arrays.stream(item.getClass().getDeclaredFields()))
.map(field -> { field.setAccessible(true); return field.get(nu) == null; } ) ) {
return true;
}
}
但是,在 field.get(nu) 处抛出 IlligalAccessException,我不明白为什么我的代码不能正常工作。
当我阅读java文档时,它的语法似乎是正确的。
请问我的代码哪部分失败了?
此外,一些json格式数据被转换为String
类型的对象,所以我还需要检查string
是否为空string
或不是。
有简单的方法吗?
最佳答案
我认为您的代码中有两个错误。
第一个:
if (itinerary.getItems().stream().flatMap //
(item -> Arrays.stream(item.getClass().getDeclaredFields()))
.map(field -> { field.setAccessible(true); return field.get(nu) == null; } ) ) {
return true;
}
.map
的结果方法是Stream<Boolean>
,不是bool表达式,所以会出现语法错误,无法编译。
第二个:
return field.get(nu) == null;
此代码将抛出 NullPointerException
而filed
是一个实例字段。方法get
在Field
可以扔一些Exception
,所以应该 try catch 它。
关于java - 在嵌套数据中查找空值和空字符串(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44296730/