Grails Command Object: How to load request.JSON into it?

偶尔善良 提交于 2019-12-05 00:24:25
Aquatoad

I'm not sure if there is anything configuration-wise to do automatic JSON parameter data binding; one thing you might be able to do is to write a Filter for your actions that take JSON request input that basically remaps request.JSON directly onto the root params map, which should in theory allow the automatic data binding to take place.

something like:

class JSONParamMapFilters {
  def filters = {
     before = {
        remapFilter(controller:'yourController', action:'update') {
           request.JSON.each { k,v ->
               params[k] = v
           }
        }
     }
  }
}

You could then extend this filter via regex/naming conventions to any applicable controller actions.

You should use parseRequest=true in UrlMappings.groovy. E.g.:

"/user/$id/$action?"(controller: "userProfile", parseRequest: true) {
    constraints {
        id matches: /^[0-9]+$/
    }
}

Then you may use params variable or bind json to a command object in a method arguments:

def index(MyCommand command){...}

Both should work. But in some cases it looses some information from json (binding to maps).

If you're not using the command object as a parameter to any controller actions then Grails won't enhance it automatically with a validate method. You need to annotate the class with @Validateable to tell Grails it should be enhanced.

http://grails.org/doc/latest/guide/validation.html#validationNonDomainAndCommandObjectClasses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!