如何在grails中解析JSON时获得实际的空值而不是JSONObject.NULL值 [英] how to get a real null value instead of a JSONObject.NULL value when parsing JSON in grails

查看:314
本文介绍了如何在grails中解析JSON时获得实际的空值而不是JSONObject.NULL值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用grails.converters.JSON库解析Grails中的一些JSON。我有一个字段,它将包含一个字符串或一个空值。当我解析JSON并获取字段时,空值将作为JSONObject.NULL类型返回。这是不正确的时候检查!=空作为JSONObject.NULL被评估为非空(不适用于空检查)

I'm trying to parse some JSON in Grails using the grails.converters.JSON library. I have a field which will contain either a string, or a null value. When I parse the JSON and get the field, the null values come back as a JSONObject.NULL type. This is not good when checking != null as JSONObject.NULL is evaluated as non-null (not good for null checks)

def obj = JSON.parse('{"date1":null,"date2":"2011-06-26T05:00:00Z"}')
def date1 = obj.date1
if (date1)
     parse(date1)   // parse error occurs here because date1 evaluates true in the if because it is JSONObject.NULL

是否有一种简单的方法可以让解析解析一个真正的空值,以便我不必检查对象是否是JSONObject.NULL。

Is there an easy way to get the parse to parse a real null value so that I don't have to check if the object is a JSONObject.NULL.

我尝试了此处的建议以供使用。 toString(),但它最终返回字符串值'null'而不是实际为空的JSONObject.NULL值。

I tried the suggestion here to use .toString(), but it ended up returning the string value 'null' instead of actual null for a JSONObject.NULL value.

推荐答案

看看: http://grails.1312388。 N4 .nabble.com / The-groovy-JSONObject-Null-td3661040.html

Ian Roberts提到了一个很好的技巧来做一个空的检查可能:

Ian Roberts mentions a nice trick to make a null check possible:

JSONObject.NULL.metaClass.asBoolean = {-> false} 

这篇关于如何在grails中解析JSON时获得实际的空值而不是JSONObject.NULL值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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