【发布时间】:2015-11-27 11:43:51
【问题描述】:
我使用 Grails 2.3.x 创建了一个 REST Web 服务,如下所示:
import grails.rest.RestfulController
class CityController extends RestfulController{
static responseFormats = ['json', 'xml']
CityController() {
super(City)
}
}
这是我的域类:
import groovy.transform.ToString
import groovy.transform.EqualsAndHashCode
/**
* City
* A domain class describes the data object and it's mapping to the database
*/
@ToString(includeNames = true, includeFields = true, excludes = 'dateCreated,lastUpdated,metaClass')
@EqualsAndHashCode
class City {
/* Default (injected) attributes of GORM */
Long id
Long version
/* Automatic timestamping of GORM */
Date dateCreated
Date lastUpdated
String cityName
String postalCode
String countryCode // either iso2 or iso3
static constraints = {
postalCode blank:false, nullable:false
cityName blank:false, nullable:false
countryCode minSize:2, maxSize:3, blank:false, nullable:false, matches: "[A-Z]+"
}
}
这是 urlMapping
class UrlMappings {
static mappings = {
"/$controller/$action?/$id?(.$format)?"{
constraints {
// apply constraints here
}
}
"/"(view:"/index")
"500"(view:'/error')
//
// RESTService api
"/api/city"(resources: 'city')
}
}
当我尝试使用 curl 获取数据时,我设法使用以下行获取结果:
curl -X GET -H "Accept:application/json" http://localhost:8080/ComuneUtenti/city
但是当我尝试将数据发布到我的 WS 时,我遇到了如下错误:
curl: (6) Could not resolve host: countryCode
curl: (6) Could not resolve host: postalCode
curl: (3) [globbing] unmatched close brace/bracket in column 6
{"errors":[{"object":"comuneutenti.City","field":"postalCode","rejected-value":null,"message":"property [postalCode] of class [class comuneutenti.City] cannot be null"},{"object":"comuneutenti.City","field":"cityName","rejected-value":null,"message":"property
[cityName] of class [class comuneutenti.City] cannot be null"},{"object":"comuneutenti.City","field":"countryCode","rejected-value":null,"message":"property[countryCode] of class [class comuneutenti.City] cannot be null"}]}
这是我的帖子:
curl -H "Content-Type:application/json" -X POST -d '{"cityName":"NewYork", "countryCode":"IT", "postalCode": "00166"}' http://localhost:8080/ComuneUtenti/api/city
我错过了什么?
我正在使用 Grails 2.3.10 可以用 Postman 调用同一个 WS。
谢谢
【问题讨论】:
-
用单引号包裹你的 json 以防止你的 shell 解析它。
-
谢谢,但我已经尝试过了,我得到了同样的结果