【问题标题】:How to tell Grails to render JSONNull as null?如何告诉 Grails 将 JSONNull 呈现为 null?
【发布时间】:2013-09-17 18:43:11
【问题描述】:

我有一个从 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"

【问题讨论】:

  • 当有人提出问题但没有反馈他是如何解决问题的,或者提供的解决方案是否正确时,你不讨厌它......
  • @Armand 对不起。我检查了我的代码,发现我最终做了什么。我在这里添加了一个答案。

标签: json grails null grails-2.0.4


【解决方案1】:

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

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

【讨论】:

  • 我今天遇到了确切的问题,并且由于这个答案,能够非常迅速地解决它。我的一个问题是:你在哪里注册对象编组器:就在你渲染 JSON 之前?如果您期望响应中有 JSONNulls,是否必须对每个这样做的方法都这样做?
  • @ashes,我在响应之前把它放在控制器中。但是,我想你可以把它放在更中心的地方,我不确定在哪里。
【解决方案2】:

我认为您可以通过在 BootStrap 中指定以下一项来修复它

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-29
    相关资源
    最近更新 更多