我使用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。

谢谢

最佳答案

您是否尝试过erichelgeson的建议?

正确的 curl 方法是

curl -H "Content-Type:application/json" -X POST -d '{"cityName":"NewYork", "countryCode":"IT", "postalCode": "00166"}' http://localhost:8080/ComuneUtenti/api/city

请注意JSON有效负载周围的单引号。

要查看实际情况,可以使用echo命令。
$ echo {"hello":"world"}
{hello:world}

$ echo '{"hello":"world"}'
{"hello":"world"}

壳正在吞噬您周围的报价。

10-07 16:21
查看更多