Problems with a POST/PUT Json RESTful request Grails

对着背影说爱祢 提交于 2019-11-30 05:30:22

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