2017-06-01 92 views
0

我想檢查我的數據是否有空值。 JSON格式的數據低於:在嵌套數據(Java)中找到空值和空字符串

"{ 

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

然而,IlligalAccessException在field.get(NU)扔了,我想不通爲什麼我的代碼不能很好地工作。 當我閱讀java文檔時,它在語法上似乎是正確的。 我可以問我的代碼哪部分失敗? 此外,某些json格式數據轉換爲String類型的對象,因此我還需要檢查string是否爲空string。 有沒有簡單的方法來做到這一點?

回答

1

我認爲你的代碼有2個錯誤。

第一:

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>,而不是一個布爾expression.So會有一個語法錯誤和不進行編譯。

第二:

return field.get(nu) == null; 

這個代碼將拋出NullPointerExceptionfiled是一個實例field.And方法getField可以拋出一些Exception,所以應儘量副漁獲物就可以了。

0
Object nu = null; 

您正試圖獲得'nu'這是一個空對象。這就是你得到一個IlligalAccessException的原因。

1

的文檔爲Field.get

返回該字段表示的字段的值,則 指定的對象上。如果 它具有原始類型,則該值將自動包裝在對象中。

請參閱它如何在指定的對象上表示?這是因爲Field對象不再與特定對象關聯。

這意味着Field.get操作需要傳遞的item對象,而不是目前要傳遞的null分配nu對象。

這看起來確實很乏味,請嘗試使用像this這樣的庫進行JSON模式驗證。

相關問題