Search code examples
jsonrestgrails-2.0grails-controller

Grails - bind JsonArray to Collection attribute


I have a REST controller that expectes a complex object in JSON format.

Let's say, A.class has an association with a collection of B.class.

class A {
    private List<B> values;
    ...
}

class B {
    private String name;
    ... 
}

The simplified controller looks like this:

def create(){
    def jsonObject = request.JSON;
    A a = new A(jsonObject);
    ....
}

Let's say, I send the follwoing JSON to the controller:

{"values":[{"name":"test1"},{"name":"test2"}]}

In the controller, the jsonObject has "values" attribute as JsonArray. I expected Grails binding constructor to bind the JsonArray "values" to the List "values" for me, but it does not. In Spring MVC, JacksonMapper does the job for me. I like something like that.

Do I have to manually iterate JsonArray and convert items in the array to a domain object by my self?


Solution

  • Using JsonSlurper, Read the json and iterate and set it to domain object.