简体   繁体   English

如何比较Java中JsonObject的空值

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

stackoverflow member i need some help from you. stackoverflow 成员我需要你的一些帮助。

I am having a JsonObject given below我有一个 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 }

i am getting parentId as null.我得到 parentId 为空。 I want to replace the parentId value from null to 0.我想将 parentId 值从 null 替换为 0。

I am trying to do it with below mentioned code我正在尝试使用下面提到的代码来做到这一点

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

but it seems not to be working.但它似乎不起作用。 What I am doing wrong here.我在这里做错了什么。

Use the following method of JsonObject to check if a value against any key is null使用 JsonObject 的以下方法检查任何键的值是否为空

public boolean isNull(java.lang.String key)

This method is used to check Null against any key or if there is no value for the key.此方法用于根据任何键检查 Null 或该键是否没有值。

check this in the documentation文档中检查这一点

Your Modified code should be like this你修改后的代码应该是这样的

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

For com.google.gson.JsonObject, I followed this :对于 com.google.gson.JsonObject,我按照以下步骤操作:

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

In my json, I have :在我的 json 中,我有:

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

For anyone using org.json.JSONObject in 2020, if you have {"key":null}对于 2020 年使用 org.json.JSONObject 的任何人,如果您有 {"key":null}

Check the value of the key by JSONObject.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)

These two methods works这两种方法有效

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

if( jsonObject.isNull("parentId") )

Because the JSONObject has its own Null class, so java primitive null is not same as Null() in JSONObject.因为 JSONObject 有自己的 Null 类,所以 java 原语null和 JSONObject 中的Null()是不一样的。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM