使用JSON在Groovy/Grails中创建对象

krs*_*ynx 6 grails groovy android grails-controller grails-domain-class

我有一个Groovy/Grails网站,用于通过JSON向Android客户端发送数据.我创建了Android客户端和Groovy/Grails网站; 并且他们可以在JSON中输出相同的对象.

我可以通过将JSON输出映射到Java对象来成功在Android中创建相应的对象,但我想知道是否可以使用JSON输出在Groovy/Grails中创建新的域对象?有没有办法将JSON输出传递给控制器​​动作,以便创建对象?

这是我要发送的JSON示例;

{
    "class":"org.icc.callrz.BusinessCard.BusinessCard",
    "id":1,
    "businessCardDesigns":[],
    "emailAddrs":[
    {
        "class":"org.icc.callrz.BusinessCard.EmailAddress",
        "id":1,
        "address":"chris@krslynx.com",
        "businessCard":{
            "_ref":"../..",
            "class":"org.icc.callrz.BusinessCard.BusinessCard"
        },
        "index":0,
        "type":{
            "enumType":"org.icc.callrz.BusinessCard.EmailAddress$EmailAddressType",
            "name":"H"
        }
    },
    {
        "class":"org.icc.callrz.BusinessCard.EmailAddress",
        "id":2,
        "address":"cb@i-cc.cc",
        "businessCard":{
            "_ref":"../..",
            "class":"org.icc.callrz.BusinessCard.BusinessCard"
        },
        "index":1,
        "type":{
            "enumType":"org.icc.callrz.BusinessCard.EmailAddress$EmailAddressType",
            "name":"W"
        }
    }
    ]
}
Run Code Online (Sandbox Code Playgroud)

"类"与我要保存的域匹配,ID是域的ID,然后businessCardDesigns和emailAddrs中的每个项目都需要使用类似方法保存(在域中,businessCardDesigns和emailAddrs是ArrayLists ).提前谢谢了!

解:

@RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
public ResponseEntity<String> createFromJson(@RequestBody String json) {
    Owner.fromJsonToOwner(json).persist();
    return new ResponseEntity<String>(HttpStatus.CREATED);
}
Run Code Online (Sandbox Code Playgroud)

Ove*_*ous 13

在我看来,使用内置的Grails JSON转换器比其他答案更容易:

import grails.converters.JSON

class PersonController {
    def save = {
        def person = new Person(JSON.parse(params.person))
        person.save(flush:true)
    }
}
Run Code Online (Sandbox Code Playgroud)

其他好处是:

  • 没有必要在任何配置文件中捣乱
  • 在分配属性之前,如果需要,可以操作生成的JSON对象
  • 在代码中发生的事情要清楚得多(我们正在解析JSON对象并在Person实体上设置属性)


Gre*_*egg 6

我知道你已经接受了一个答案,但如果我正确地阅读你的问题,就会有一种内置的"Grails"方式来做到这一点.

在URLMappings.groovy中为您的操作创建一个条目,然后打开请求解析.例如,我创建RESTful映射,如下所示:

"/api/bizCard/save"(controller: "businessCard", parseRequest: true) {
   action = [POST: "save"]
}
Run Code Online (Sandbox Code Playgroud)

然后在你的控制器

def save = {
   def businessCardInstance = new BusinessCard(params.businessCard)
   ....
   businessCardInstance.save(flush:true)
}
Run Code Online (Sandbox Code Playgroud)