簡體   English   中英

如何比較Java中JsonObject的空值

[英]How to compare null value from the JsonObject in java

stackoverflow 成員我需要你的一些幫助。

我有一個 JsonObject 下面給出

{
"Id": null,
"Name": "New Task",
"StartDate": "2010-03-05T00:00:00",
"EndDate": "2010-03-06T00:00:00",
"Duration": 1,
"DurationUnit": "d",
"PercentDone": 60,
"ManuallyScheduled": false,
"Priority": 1,
"parentId": null,
"index": 2,
"depth": 1,
"checked": null }

我得到 parentId 為空。 我想將 parentId 值從 null 替換為 0。

我正在嘗試使用下面提到的代碼來做到這一點

if(jsonObject.get("parentId") == null || jsonObject.get("parentId") == "")
    {
        System.out.println("inside null");
        jsonObject.put("parentId", 0);
    }
    else
    {
        System.out.println("inside else part");
        //jsonObject.put("parentId", jsonObject.getInt("parentId"));
        jsonObject.put("parentId", 0);
    }

但它似乎不起作用。 我在這里做錯了什么。

使用 JsonObject 的以下方法檢查任何鍵的值是否為空

public boolean isNull(java.lang.String key)

此方法用於根據任何鍵檢查 Null 或該鍵是否沒有值。

文檔中檢查這一點

你修改后的代碼應該是這樣的

if(jsonObject.isNull("parentId"))
    {
        System.out.println("inside null");
        jsonObject.put("parentId", 0);
    }
    else
    {
        System.out.println("inside else part");
        //jsonObject.put("parentId", jsonObject.getInt("parentId"));
        jsonObject.put("parentId", 0);
    }

對於 com.google.gson.JsonObject,我按照以下步驟操作:

boolean isIdNull = jsonObject.get("Id").isJsonNull();

在我的 json 中,我有:

"Id":null
if(jsonObject.isNull("parentId")){
    jsonObject.put("parentId", 0);
}

對於 2020 年使用 org.json.JSONObject 的任何人,如果您有 {"key":null}

通過 JSONObject.NULL 檢查鍵的值

JSONObject json = new JSONObject("{"key":null}");
Object value = json.get("key");
if (value == JSONObject.NULL){
  ...
}

試試下面的代碼。

if(jsonObject.isNull("parentId") || jsonObject.get("parentId").equals(""))

嘗試使用下一個代碼

int parentId = jsonObject.optInt("parentId", 0)

這兩種方法有效

if( jsonObject.get("parentId").equals(null) )

if( jsonObject.isNull("parentId") )

因為 JSONObject 有自己的 Null 類,所以 java 原語null和 JSONObject 中的Null()是不一樣的。

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM