【问题标题】:How to pass object as JSON to a POST or PUT request in grails如何将对象作为 JSON 传递给 grails 中的 POST 或 PUT 请求
【发布时间】:2015-06-27 15:23:36
【问题描述】:

我在 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 = {
    }
  } 

在引导程序中,我可以按如下方式创建新的人员条目

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 方法进行插入和更新。

【问题讨论】:

  • 你能告诉我你的 /app/person/index 控制器的来源吗?
  • 我没有一个名为 PersonController 的控制器。当我使用 "/app/person"(resources: "person") 这个 url 映射时,对 Person 对象的 crud 操作由 grails 自动设置。

标签: rest grails grails-orm grails-domain-class grails-2.4


【解决方案1】:

问题在于您发送的 JSON。虽然它是有效的 JSON,但它不是您资源的正确表示。你的 JSON 应该是:

{
   "name":"john",
   "address": 
   {
      "house":"sample address"
   }
}

从上面可以看出,address 属性实际上是一个嵌套对象,而不是像您发送的 String

【讨论】:

【解决方案2】:

此外,您是否查看过http://grails.github.io/grails-doc/latest/guide/webServices.html 上的指南? 特别是我希望你检查部分:

grails.mime.types = [
    …
    json:          ['application/json', 'text/json'],
    …
    xml:           ['text/xml', 'application/xml']
]

请记住,当您使用 PersonInstance 处理 '/app/person' 时,实际上是在执行 '/app/person/index/ ' 与 PersonInstance (所以如果需要调试它的源)。

还要仔细检查课程中的“id”列。

【讨论】:

    猜你喜欢
    • 2023-03-21
    • 1970-01-01
    • 2013-05-25
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 2014-05-07
    • 1970-01-01
    • 2014-01-30
    相关资源
    最近更新 更多