在grails中使用HTTP GET调用时,字段值呈现为null

时间:2014-05-28 07:56:16

标签: grails groovy gorm grails-2.0

这是Person的域类:

 package com.sample
 class Person {
    String id
    String name
    Integer age
    Address address
static hasMany = [pets:Pet, alias: String, aliases : Alias]

static mapWith = "mongo"
 static constraints = {
      address nullable:true
      pets nullable :true
 }
}

这是地址的域类:

 package com.sample

 class Address {

   String address
   static mapWith = "mongo"
   static constraints = {
           address maxSize: 1000
   }
 }

这是PersonController中的ShowPerson方法:

 def showPerson(String name,String age){

            if(Person.findByAgeAndName(age,name) != null) {
                    render Person.findByAgeAndName(age,name) as JSON
            }
            else {

                def addobj = new Address(address: "kondapur")
                addobj.save(flush:true)

                def pet1 = new Pet(name : "Dog", breed : "A")
                pet1.save(flush:true)

                def alias1 = "ALIAS1"
                def alias2 = "ALIAS2"

                def list = ["A"]
                def aliases1 = new Alias(aliasname : [list])
                aliases1.save(flush:true)

                def person = new Person(name : name, age : age,  address : addobj, pets : [pet1], alias : [alias1, alias2], aliases : [aliases1])

                person.save()   

                render person as JSON
            }

        }

最初,DB中没有人(暗示Perers.findByAgeAndName(年龄,名称)== null)因此它会创建一个新对象并将其保存在数据库中)。所以当我点击网址时

 > http://localhost:8080/TestJson/showPerson/sample/23

现在的输出是:

name field of address is seen

现在当我点击同一个网址(暗示Person.findByAgeAndName(年龄,名字)!= null)因此它从数据库中获取):

现在的输出是:

name field of address became null

在数据库中,地址保存为:

saved correctly

在数据库中,此人保存为:

The id of the address is stored

有人能告诉我如何获取地址(红色环绕)为非null并在我尝试从数据库中获取保存的对象时获取相应的值(即在这种情况下为kondapur而非null)

1 个答案:

答案 0 :(得分:-1)

Grails JSON marshaller默认情况下不添加嵌套类,您必须添加一行代码:

     def showPerson(String name,String age){

   JSON.use('deep')// <============================== Add this line

                if(Person.findByAgeAndName(age,name) != null) {
                        render Person.findByAgeAndName(age,name) as JSON
                }
            else {

                def addobj = new Address(address: "kondapur")
                addobj.save(flush:true)

                def pet1 = new Pet(name : "Dog", breed : "A")
                pet1.save(flush:true)

                def alias1 = "ALIAS1"
                def alias2 = "ALIAS2"

                def list = ["A"]
                def aliases1 = new Alias(aliasname : [list])
                aliases1.save(flush:true)

                def person = new Person(name : name, age : age,  address : addobj, pets : [pet1], alias : [alias1, alias2], aliases : [aliases1])

                person.save()   



                render person as JSON
            }

        }