How to properly attach a list of objects to a Grails command?

I am trying to figure out how to deserialize and inspect nested objects in a JSON request into a Grails 2.1.1 command object.

I currently have a command object in my controller that has several basic properties, and then a list of domain objects,

protected static class CustomCommand { String name String description List<DomainObject> objs } 

And the JSON body for my POST request,

 { name: 'test name', description: 'test description', objs: [ { name: 'test sub object', description: 'test description' } ] } 

I see a command object created with an empty array. Any idea how I can get sub objects in my JSON body to deserialize into a command object and then test them?

I used to work on this by manually creating an object from the parameter map and checking it directly, but this seems like a workaround that doesn't use everything Grails has to offer.

+6
source share
2 answers

I never had to work under Grails 2.1.1, but apparently it was fixed in Grails 2.3 ,

Binding request body for command objects If the request is for the action of the controller that receives the command object and the request includes the body, the body will be parsed and used to bind data to the command object. This makes it easier to use cases where a request includes a JSON or XML body (for example) that can be bound to a command object. See the command documentation for more details.

+1
source

We had a similar problem with the attached data of the message to the list inside the command. Our approach to work was to determine the default value for the elements of the collection:

 class MyCommand { List<MyClass> items= [].withLazyDefault { new MyClass() } } 

After that, the mail data was correctly bound to the list. I think the reason is that Groovy ignores the generic type parameter in the list and does not know which object to instantiate at runtime.

I'm not sure if this works in your case, but it might be worth a try

Update:

I used this a few minutes ago:

 public static class MyCommand { String foo List<Bar> bars public String toString() { return "foo: " + foo + ", bars: " + bars } } public static class Bar { String baz } 

:

 def test() { println new MyCommand(request.JSON) } 

I wrote json using jquery:

 $.ajax({ type: "POST", url: '...', data: JSON.stringify({ 'foo': '12345', bars: [ {baz: '1'}, {baz: '2'} ] }), contentType : 'application/json', }); 

Controller output:

 foo: 12345, bars: [[baz:1], [baz:2]] 

So this works: o

+7
source

Source: https://habr.com/ru/post/953204/


All Articles