这是Person的 Realm 类:
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
}
}
这是Address的域类:
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中没有人员(这意味着Person.findByAgeAndName(age,name)== null)因此它创建了一个新对象并将其保存在数据库中。所以当我点击网址
> http://localhost:8080/TestJson/showPerson/sample/23
现在的输出是:
现在,当我重新单击相同的URL时(暗示Person.findByAgeAndName(age,name)!= null)因此它是从数据库中获取的:
现在的输出是:
地址在数据库中另存为:
该人在数据库中另存为:
有人可以告诉我如何尝试从数据库中获取保存的对象(即本例中的kondapur而不是null)时,如何获取不为null的地址(红色圆圈)并获取相应的值。
最佳答案
默认情况下,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
}
}
关于grails - 在grails中使用HTTP GET调用时,字段值呈现为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23905819/