Question

I have a JSON object returned from Groovy's HTTPBuilder. THE JSON contains some null values represented as JSONNull objects. The problem is that when I try to render the JSON back in a response, I get an error when it tries to render the JSONNull. I get a response that is only partially rendered. I want it to render as "null". How do I do this?

Code:

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

Error:

| 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

Partially Rendered Output:

[{"keyWithNullValue":{"array":false,"class":"net.sf.json.JSONNull"
Was it helpful?

Solution

I used the following code to render JSONNull as an empty string.

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

OTHER TIPS

I think you can fix it by specifying the below one in BootStrap

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top