我在grails中使用 Restful 服务。我有2个类Person
import grails.rest.Resource
@Resource(formats=['json', 'xml'])
class Person {
String name
Address address
static constraints = {
}
}
和
Address
为 import grails.rest.Resource
@Resource(formats=['json', 'xml'])
class Address {
String house
static constraints = {
}
}
在bootstrap中,我可以创建如下的新人员条目
new Person(name:"John" , address: new Address(house:"John Villa").save()).save();
但是问题是我想使用带有JSON数据的POST请求来做同样的事情。
我将UrlMappings.Groovy设置为
"/app/person"(resources: "person", includes: ['index', 'show', 'save', 'update', 'delete', 'create', 'patch'])
"/app/address"(resources: "address", includes: ['index', 'show', 'save', 'update', 'delete', 'create', 'patch'])
然后我尝试通过使用JSON数据向``/ app / person''发送POST请求来尝试使用POSTMAN rest客户端
{
"name":"john" ,
"address": "{'house' :'sample address' }"
}
但它给出错误422无法处理的实体。
如何使用JSON执行相同操作?我想使用POST和PUT方法进行插入和更新。
最佳答案
问题在于您发送的JSON。尽管它是有效的JSON,但它并不是您资源的正确表示形式。您的JSON应该是:
{
"name":"john",
"address":
{
"house":"sample address"
}
}
从上面可以看到,
address
属性实际上是一个嵌套对象,而不是发送的String
。
关于rest - 如何在grails中将对象作为JSON传递给POST或PUT请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31090300/