2013-05-29 127 views
8

嗨,我有一個grails restful代碼。我做了完美的Json獲取和刪除請求。 我的問題是: 我想用json做一個Put或post請求,但是如果我使用一個程序來做到這一點,它有一個錯誤,我不能這樣做! 這裏我的代碼: 一類:POST/PUT Json RESTful請求的問題Grails

package catalogo.json 
class Catalogo { 
    String nombre 
    String descripcion 
    String url 
    Set <Parametros>parametros =[] 
    static hasMany = [parametros:Parametros] 
    int numeroParametros = parametros.size() 
} 

與其他類:

package catalogo.json 

class Parametros { 
    String tipoParametro 
    String json 
    static constraints = { 
    tipoParametro(nullable:true) 
    json(nullable:true) 
    } 
} 

我不知道如何把我的JSON的請求。當我說出錯的時候,這是錯誤。

示例:
I PUT POST請求。 體application/json(或text/json是同樣的錯誤)字符集UTF-8

{"descripcion": "bla", "nombre" : "lalala", "numeroParametros":3, "parametros":[{     
"tipoParametro":"string", "json":"bla"}],"url":"http://www.google.com"} 

而且這裏的錯誤:

Could not create new Catalogo due to errors: 
grails.validation.ValidationErrors: 3 errors 
Field error in object 'catalogo.json.Catalogo' on field 'descripcion': rejected value [null]; codes [catalogo.json.Catalogo.descripcion.nullable.error.catalogo.json.Catalogo.descripcion,catalogo.json.Catalogo.descripcion.nullable.error.descripcion,catalogo.json.Catalogo.descripcion.nullable.error.java.lang.String,catalogo.json.Catalogo.descripcion.nullable.error,catalogo.descripcion.nullable.error.catalogo.json.Catalogo.descripcion,catalogo.descripcion.nullable.error.descripcion,catalogo.descripcion.nullable.error.java.lang.String,catalogo.descripcion.nullable.error,catalogo.json.Catalogo.descripcion.nullable.catalogo.json.Catalogo.descripcion,catalogo.json.Catalogo.descripcion.nullable.descripcion,catalogo.json.Catalogo.descripcion.nullable.java.lang.String,catalogo.json.Catalogo.descripcion.nullable,catalogo.descripcion.nullable.catalogo.json.Catalogo.descripcion,catalogo.descripcion.nullable.descripcion,catalogo.descripcion.nullable.java.lang.String,catalogo.descripcion.nullable,nullable.catalogo.json.Catalogo.descripcion,nullable.descripcion,nullable.java.lang.String,nullable]; arguments [descripcion,class catalogo.json.Catalogo]; default message [La propiedad [{0}] de la clase [{1}] no puede ser nulo] 
Field error in object 'catalogo.json.Catalogo' on field 'nombre': rejected value [null]; codes [catalogo.json.Catalogo.nombre.nullable.error.catalogo.json.Catalogo.nombre,catalogo.json.Catalogo.nombre.nullable.error.nombre,catalogo.json.Catalogo.nombre.nullable.error.java.lang.String,catalogo.json.Catalogo.nombre.nullable.error,catalogo.nombre.nullable.error.catalogo.json.Catalogo.nombre,catalogo.nombre.nullable.error.nombre,catalogo.nombre.nullable.error.java.lang.String,catalogo.nombre.nullable.error,catalogo.json.Catalogo.nombre.nullable.catalogo.json.Catalogo.nombre,catalogo.json.Catalogo.nombre.nullable.nombre,catalogo.json.Catalogo.nombre.nullable.java.lang.String,catalogo.json.Catalogo.nombre.nullable,catalogo.nombre.nullable.catalogo.json.Catalogo.nombre,catalogo.nombre.nullable.nombre,catalogo.nombre.nullable.java.lang.String,catalogo.nombre.nullable,nullable.catalogo.json.Catalogo.nombre,nullable.nombre,nullable.java.lang.String,nullable]; arguments [nombre,class catalogo.json.Catalogo]; default message [La propiedad [{0}] de la clase [{1}] no puede ser nulo] 
Field error in object 'catalogo.json.Catalogo' on field 'url': rejected value [null]; codes [catalogo.json.Catalogo.url.nullable.error.catalogo.json.Catalogo.url,catalogo.json.Catalogo.url.nullable.error.url,catalogo.json.Catalogo.url.nullable.error.java.lang.String,catalogo.json.Catalogo.url.nullable.error,catalogo.url.nullable.error.catalogo.json.Catalogo.url,catalogo.url.nullable.error.url,catalogo.url.nullable.error.java.lang.String,catalogo.url.nullable.error,catalogo.json.Catalogo.url.nullable.catalogo.json.Catalogo.url,catalogo.json.Catalogo.url.nullable.url,catalogo.json.Catalogo.url.nullable.java.lang.String,catalogo.json.Catalogo.url.nullable,catalogo.url.nullable.catalogo.json.Catalogo.url,catalogo.url.nullable.url,catalogo.url.nullable.java.lang.String,catalogo.url.nullable,nullable.catalogo.json.Catalogo.url,nullable.url,nullable.java.lang.String,nullable]; arguments [url,class catalogo.json.Catalogo]; default message [La propiedad [{0}] de la clase [{1}] no puede ser nulo] 

編輯在這裏我的控制器:

package catalogo.json 

import grails.converters.JSON 

class CatalogoController { 

def index = {  
switch(request.method){ 
    case "POST": 
     def catalogo = new Catalogo(params.catalogo) 
     if(catalogo.save()){ 
      response.status = 201 // Created 
      render catalogo as JSON 
     } 
     else{ 
      response.status = 500 //Internal Server Error 
      render "Could not create new Airport due to errors:\n               
         ${catalogo.errors}" 
     } 
     break 
    case "GET": 
    if(params.id){render Catalogo.findById(params.id) as JSON} 
    else{render Catalogo.list() as JSON}   
    break 
case "PUT": 
def catalogo = Catalogo.findById(params.catalogo.id) 
    catalogo.properties = params.catalogo 
    if(catalogo.save()){ 
    response.status = 200 // OK 
    render catalogo as JSON 
    } 
    else{ 
    response.status = 500 //Internal Server Error 
    render "Could not create new Catalogo due to errors:\n ${catalogo.errors}" 
    } 
    break  
    case "DELETE": 
    if(params.id){ 
    def catalogo = Catalogo.findById(params.id) 
    if(catalogo){ 
     catalogo.delete() 
     render "Successfully Deleted." 
    } 
    else{ 
     response.status = 404 //Not Found 
     render "${params.id} not found." 
    } 
    } 
    else{ 
    response.status = 400 //Bad Request 
    render """DELETE request must include the ID code 
       Example: /rest/catalogo/id 
    """ 
    } 
    break 
    } 
} 
    def list = { 
    if(!params.max) params.max = 10 
    def list = Catalogo.list(params) 
    withFormat{ 
    html{ 
     return [catalogoList:list] 
    } 
    json{ 
     render list as JSON 
    } 
    } 
} 
} 

感謝

+1

你如何在控制器中保存'Catalogo'? – dmahapatro

+0

觀看更新:)謝謝!更新中的 – natijauskas

回答

18

以下是應該如何在控制器中完成: -

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客戶:

你是如何測試REST WS?你應該有一個REST客戶端來測試服務?或者您可以使用REST console extension in Chrome來測試您的服務。您也可以使用grails插件rest-client-builder來測試您的服務。基本而言,如果您不想要任何客戶端實現,那麼至少需要一個腳本來測試您的服務。在這種情況下,HttpBuilder將會很有用。需要這樣的東西來測試你的服務

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 
    } 
} 
+0

,這裏是我的控制器。我只想知道如何將json放在request.its中,而不是關於這個json的代碼,以便在resful客戶端中執行請求來嘗試它。 – natijauskas

+0

無論您使用哪種REST客戶端,只需將json設置爲'request.JSON =「您的json在這裏」,就可以按照我在答案中提到的方式訪問JSON。 – dmahapatro

+0

但是,如果我把這個JSON請求,我有505錯誤,我知道爲什麼。請問我必須改變? {「descripcion」:「bla」,「nombre」:「lalala」,「numeroParametros」:3,「parametros」:[{tipoParametro「:」string「,」json「:」bla「}],」url 「:」http://www.google.com「}我在哪裏把request.JSON =」你的json在這裏「?在客戶端?感謝 – natijauskas