如何在Java中比较JsonObject中的空值 [英] How to compare null value from the JsonObject in java

查看:363
本文介绍了如何在Java中比较JsonObject中的空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

stackoverflow成员,我需要您的帮助.

stackoverflow member i need some help from you.

我下面有一个JsonObject

I am having a JsonObject given below

{
"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设置为null.我想将parentId值从null替换为0.

i am getting parentId as null. I want to replace the parentId value from null to 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.

推荐答案

使用JsonObject的以下方法检查针对任何键的值是否为空

Use the following method of JsonObject to check if a value against any key is null

public boolean isNull(java.lang.String key)

此方法用于针对任何键或是否没有键值检查Null.

This method is used to check Null against any key or if there is no value for the key.

文档

您修改后的代码应该是这样

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

这篇关于如何在Java中比较JsonObject中的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆