如何告诉Grails将JSONNull渲染为null?

时间:2013-09-17 18:43:11

标签: json grails null grails-2.0.4

我有一个从Groovy的HTTPBuilder返回的JSON对象。 JSON包含一些表示为JSONNull对象的空值。问题是当我尝试在响应中渲染JSON时,我在尝试渲染JSONNull时出现错误。我得到的回复只是部分呈现的。我希望它呈现为“null”。我该怎么做?

代码:

render(contentType: "text/json") {
    listOfJSONObjectsThatIncludeJSONNulls
}

错误:

| Error 2013-09-17 11:33:56,965 [http-bio-8080-exec-4] ERROR errors.GrailsExceptionResolver  - JSONException occurred when processing request: [GET] /my/action
Object is null. Stacktrace follows:
Message: Object is null
   Line | Method
->>  69 | isEmpty        in net.sf.json.JSONNull
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|   199 | value          in grails.converters.JSON
|   162 | convertAnother in     ''
|   199 | value          in     ''
|   162 | convertAnother in     ''
|   199 | value          in     ''
|   162 | convertAnother in     ''
|   199 | value          in     ''
|   162 | convertAnother in     ''
|   199 | value          in     ''
|   162 | convertAnother in     ''
|   199 | value          in     ''
|   162 | convertAnother in     ''
|   199 | value          in     ''
|   134 | render . . . . in     ''
|   150 | render         in     ''
|    63 | doCall . . . . in myproject.MyController$_index_closure1_closure2_closure4$$EOHirVeS
|   477 | doRequest      in groovyx.net.http.HTTPBuilder
|   417 | doRequest . .  in     ''
|   349 | request        in     ''
|    43 | doCall . . . . in myproject.MyController$_index_closure1$$EOHirVeS
|   477 | doRequest      in groovyx.net.http.HTTPBuilder
|   268 | get . . . . .  in     ''
|    31 | index          in myproject.MyController$$EOHirVeS
|   895 | runTask . . .  in java.util.concurrent.ThreadPoolExecutor$Worker
|   918 | run            in     ''
^   680 | run . . . . .  in java.lang.Thread

部分呈现的输出:

[{"keyWithNullValue":{"array":false,"class":"net.sf.json.JSONNull"

2 个答案:

答案 0 :(得分:6)

我使用以下代码将JSONNull呈现为空字符串。

grails.converters.JSON.registerObjectMarshaller(JSONNull, { return "" })

答案 1 :(得分:1)

我认为您可以通过在BootStrap

中指定以下内容来解决此问题
JSONObject.NULL.metaClass.asBoolean = {-> false} 

查看:how to get a real null value instead of a JSONObject.NULL value when parsing JSON in grails