Trt Trt
Trt Trt

Reputation: 5532

Grails JSON Converter

I have a method in my main controller that return a string that I want to render as JSON. So I am importing "import grails.converters.JSON" and calling

myMethod() as JSON

, and it works fine. But when I need to get some details of the json response in my integration test.

So in my integration test I have:

void testfoo() {
    def bar = controller.myMethod();
    def bar.name; //fails
    JSON.parse(bar.toString()).name; // doesn't fail
    ....
    ..
}

any idea why I need to convert it to a string and then again to a JSON, since it already a JSON?

Upvotes: 1

Views: 3440

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122364

The value you get back from your method is a grails.converters.JSON, which is not a directly accessible JSON tree as such, but simply an object that knows how to serialize itself as JSON when required. If you want direct access to the JSON tree structure then you need to tell the grails.converters.JSON object to serialize itself and then pass that JSON to JSON.parse to turn it into a JSONElement (or one of its subclasses, in this case presumably a JSONObject).

Upvotes: 3

Related Questions