Problems with a POST/PUT Json RESTful request Grails
Here is how it should be done in controllers:-
def index() { //JSON Object is not bound to params it is bound to request in POST/PUT def jsonObj = request.JSON //You can also use JSON.parse() to get a JSON object if the request payload has JSON as string //def jsonObj = JSON.parse(request) //You will not be able to save the inner JSONArrays if you // directly bind the jsonObj to the domain. in order to save //convert them to the proper domain objects otherwise you would get validation errors for parametros def catalogParams = [] as Set jsonObj.parametros.each{ catalogParams << new CatalogParams(it) } //Set the domain back to the jsonObj jsonObj.parametros = catalogParams //Bind to catalog def catalog = new Catalog(jsonObj) //Synonymous to new Catalog(params) but here you cannot use params. //Save if (!catalog.save(flush: true)){ catalog.errors.each { println it } } render catalog}//Domain Classes:-class CatalogParams { String tipoParametro String json static constraints = { tipoParametro(nullable:true) json(nullable:true) }}class Catalog { String nombre String descripcion String url Set<CatalogParams> parametros = [] static hasMany = [parametros: CatalogParams] int numeroParametros = parametros.size()}
REST Client:
How are you testing the REST WS? You should have a REST client to test the service? Or you can use REST console extension in Chrome to test your service. You can also use a grails plugin rest-client-builder to test your service. In basic terms, if you do not want any client implementation then atleast a script to test your service. HttpBuilder will be useful in this case:. Something like this is required to test your service
import groovyx.net.http.HTTPBuilderdef http = new HTTPBuilder('http://yourdomain.com/catalog/')http.request(POST, JSON) { requestContentType = ContentType.APPLICATION_JSON // coreesponding to application/json body = ["descripcion": "bla", "nombre" : "lalala", "numeroParametros":3, "parametros":[{ "tipoParametro":"string", "json":"bla"}],"url":"google.com"] response.success = { resp -> assert resp.statusLine.statusCode == 200 }}