在Grails 2.3.3中接收复杂的json对象

时间:2013-12-12 14:04:36

标签: json rest grails grails-domain-class

我遇到类似的问题:Grails get child domain objects

我只是粘贴链接中的域类代码,以便帖子可读:

class Parent{
   String name
   static hasMany = [childs:Child] 
   static constraints = {
   }
}

class Child{
   String name
   static belongsTo = [parent:Parent]
   static constraints={}
}

我为Parrent对象创建了自定义marshaller,产生类似下面的内容。 如何接收和保存像那样的复杂JSON对象?(我想接收相同的对象,例如marshaller为我生成的对象)

[{"class":"project.Parent","id":1,"name":"name1",
  "childs":[{"class":"Child","id":1,"name":"childname1"},
            {"class":"Review","id":2,"name":"childname2"}
           ]
}]

除了JSON,如果我有所有参数,比如“name”等,我的应用程序中的默认保存代码是:

def parrent = new Parrent("parr_name") 
parrent.save()
def child = new Child("child_name", parrent)
child.save()  

我是否必须单独发送JSON对象?或者我可以收到复杂的json并拖出args的地图?以这种方式实现显示JSON的编组器是否能够以类似的格式接收一个? 我使用的是grails v2.3.3

1 个答案:

答案 0 :(得分:2)

Grails 2.3。*附带了一个重新定义的数据绑定框架,您可以将JSON有效负载(在大多数情况下从POST请求)直接绑定到域类。

它的工作方式与您为响应JSON量身定制的marshaller相同。在早期版本的Grails中使用CommandObjects的方式也可以使用它。举个例子:

class Parent {
    String name
    static hasMany = [children:Child]
}

class Child {
    String name
    static belongsTo = [parent:Parent]
}

//In Controller
class ParentController {

    //Directly binding the payload JSON to Parent domain class
    //Caveat here is if the corresponding Parent domain matching the id in the
    //payload is not found then "parent" parameter 
    //in the below action will be null 
    def save(Parent parent) {
        println "Parent Data $parent"
        println "Child Data $parent.children"

        render "Parent Data $parent and child data $parent.children"

        //or Do other stuff
    }
}

//Assuming you have parent and child already present
class BootStrap {
    def init = { servletContext ->
        def parent = new Parent(name: "name1")

        def child1 = new Child(name: "childname1")
        def child2 = new Child(name: "childname2")

        parent.addToChildren(child1)
        parent.addToChildren(child2)

        parent.save(flush: true, failOnError: true)
    }
}

//and payload as
POST http://localhost:8080/YourApp/parent/save
Content-Type: application/json

{"class":"project.Parent","id":1,"name":"name1",
  "childs":[{"class":"Child","id":1,"name":"childname1"},
            {"class":"Child","id":2,"name":"childname2"}
           ]
}

//curl command like
curl -X POST 
     -H "Content-Type: application/json" 
     -d '{"class":"project.Parent","id":1,"name":"name1",
          "childs":[{"class":"Child","id":1,"name":"childname1"},
                    {"class":"Child","id":2,"name":"childname2"}
                   ]
         }' 
      http://localhost:8080/YourApp/parent/save

您应该能够直接将JSON有效内容绑定到Parent域(带子节点)。如果您使用的是url参数而不是JSON,则同样适用。