[英]Grails render encodeAsJSON GORM with ObjectId (mongodb)
這是一個模型
import org.bson.types.ObjectId
class Foo{
ObjectId id
String name
}
這是一個動作
def action = {
render(status:200, contentType:"application/json") {
['foo' : Foo.get(params.id)]
}
}
該動作將返回類似這樣的內容
{"foo":{"class":"Foo","id":{"class":"org.bson.types.ObjectId","inc":340737392,"machine":-2019394572,"new":false,"time":1299107672000},"name":"fooName"]}
我的問題是,我該如何在json中發送ObjectId的toString,我不要這個
"id":{"class":"org.bson.types.ObjectId","inc":340737392,"machine":-2019394572,"new":false,"time":1299107672000}
我想要更多類似的東西
"id":18893828183
我知道我可以選擇想要的參數:
def foo = Foo.get(params.id)
['foo' : 'Foo' :[id:foo.id.toString(), name:foo.name]]
但是我不想總是聲明要作為json返回的內容,我想返回所有對象Foo.get(params.id).encodeAsJSON()...
有沒有一種方法可以重寫encodeAsJSON()
我已經嘗試添加
class Foo{
....
static transients : ['idStr']
def getIdStr(){
return this.id.toString()
}
....
}
但是在encodeAsJSON()中被忽略
我什至嘗試過
class Foo{
....
def toJSON(){
def obj = this.encodeAsJSON()
def json = new JsonSlurper().parseText(obj);
json.idString = this.id.toString()
return json.toString()
}
...
}
這個“作品”,但是不。
因為在此之后
render(status:200, contentType:"application/json") {
['foo' : Foo.get(params.id).toJSON()]
}
渲染對json進行編碼,因此所有內容都被“轉義了”。
那么您認為解決方案是什么,而構建器總是定義我要返回的內容?
希望,我已經明確了我的問題...。
我將從構建器開始,希望您能給我另一個更簡單/更簡潔的解決方案...
謝謝
編輯我只是做了一個將對象作為地圖返回的方法,所以現在我做這樣的事情
render(status:200, contentType:"application/json") {
['foo' : getFooAsMap(Foo.get(params.id))]
}
在Bootstarp.groovy上注冊該對象Marshaller,它將像魅力一樣工作
import grails.converters.JSON
import org.bson.types.ObjectId
JSON.registerObjectMarshaller(ObjectId) {
return it.toStringMongod()
}
你也可以這樣做:
def domainObj = YourDomainClass.get(params.id)
Map props = [:]
def domain = new DefaultGrailsDomainClass(YourDomainClass.class)
domain.properties.each{
props[it.name] = domainObj[it.name]
}
props["id"] = domainObj.id.toString()
render props as JSON
或更妙的是,使其可重用。 將此閉合放置在方便的位置:
def mongoObjectResponse = {dobj ->
Map props = [:]
def domain = new DefaultGrailsDomainClass(YourDomainClass.class)
domain.properties.each{
props[it.name] = dobj[it.name]
}
props["id"] = dobj.id.toString()
// I like to leave room in my responses for messages and such
message = ""
obj = props
}
然后從您的控制器中這樣調用:
return render(contentType: "text/json") {
mongoObjectResponse.delegate = delegate
mongoObjectResponse(domainObj)
}
只需將您的域類定義為
class Foo {
String id
String name
}
代替ObjectId
如果您要對您的域類進行JSON編碼到網絡上,我想知道ObjectId是否不是最佳選擇? GORM / MongoDB集成允許您對ID使用任何類型。 您可以將其聲明為String類型(如果您出於隨機性而希望將其分配為ObjectId的toString),則不必擔心這種混亂。 以后可能會分析/處理由此引起的任何性能/可伸縮性問題,但是除非它是一個非常大的應用程序,否則我不希望有任何問題。
在地圖中使用GStrings,您將獲得ObjectId的數字值。 例如
render ["foo":"$foo.id"] as JSON
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.