在 grails 中解析 JSON 时如何获取真正的 null 值而不是 JSONObject.NULL 值
我正在尝试使用 grails.converters.JSON 库解析 Grails 中的一些 JSON。我有一个包含字符串或空值的字段。当我解析 JSON 并获取字段时,空值以 JSONObject.NULL 类型返回。检查 != null 时这不好,因为 JSONObject.NULL 被评估为非空(不适合空检查)
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。
我尝试了此处使用 .toString() 的建议,但是它最终返回字符串值“null”,而不是 JSONObject.NULL 值的实际 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
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能会发现这更有用且更自然
You may find this more useful and natural
看一下: http://grails.1312388.n4 .nabble.com/The-groovy-truth-of-JSONObject-Null-td3661040.html
伊恩·罗伯茨提到了一个可以进行空检查的好技巧:
Have a look at: http://grails.1312388.n4.nabble.com/The-groovy-truth-of-JSONObject-Null-td3661040.html
Ian Roberts mentions a nice trick to make a null check possible:
我想我找到了一个更好的解决方案,其中包括通过复制 JSONObject.java 来覆盖
JSONObject.NULL
内部类的toString()
方法实现code> 文件添加到 Grailssrc/java
项目中,然后将实现更改为:在类路径中使用这个新类重新启动后,类加载器将使用您的
JSONObject
类而不是 Grails 中打包的那个依赖关系。确保将其与原件放在同一个包装中。
有关更多详细信息,您可以访问此处: https://github.com/grails/grails-core /issues/9129
希望有帮助:-)
I think I found a better solution, which consists in overriding the
toString()
method implementation of theJSONObject.NULL
inner class by copying theJSONObject.java
file into your Grailssrc/java
project and then changing the implementation to this:Once you restart with this new class in your classpath, the classloader will use your
JSONObject
class instead of the one packaged in the Grails dependencies.Make sure you keep it in the same package as the original.
For more details you can go here: https://github.com/grails/grails-core/issues/9129
Hope it helps :-)