我有一个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"
}
}
]
}
“class”与我要保存的域匹配,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);
}
答案 0 :(得分:12)
在我看来,使用内置的Grails JSON转换器比其他答案更容易:
import grails.converters.JSON
class PersonController {
def save = {
def person = new Person(JSON.parse(params.person))
person.save(flush:true)
}
}
其他好处是:
答案 1 :(得分:6)
我知道你已经接受了答案,但如果我正确地阅读你的问题,那就有内置的“Grails”方式来做这件事。
在URLMappings.groovy中为您的操作创建一个条目,然后启用请求解析。例如,我创建了RESTful映射,如下所示:
"/api/bizCard/save"(controller: "businessCard", parseRequest: true) {
action = [POST: "save"]
}
然后在你的控制器
def save = {
def businessCardInstance = new BusinessCard(params.businessCard)
....
businessCardInstance.save(flush:true)
}
答案 2 :(得分:1)