雖然它可能是諸如簡單的領域有點大材小用,而你可能會因爲剛剛返回Map
而丟失數據,問題仍然有效。
你如何註冊自定義命名marshallers?
通常情況下,您會在grails-app/conf/BootStrap.groovy
(或新文件grails-app/conf/CustomMarshallersBootStrap.groovy
,如果您想保持清潔)內部執行此操作。這樣的例子可能是這樣的:
// Bootstrap.groovy
import grails.converters.JSON
import com.example.User
class BootStrap {
def init = { servletContext ->
JSON.createNamedConfig("userEmployeeView", {
JSON.registerObjectMarshaller(User) { User o ->
return [
username: o.username,
empId: o.empId
]
}
})
JSON.createNamedConfig("userOtherView", {
JSON.registerObjectMarshaller(User) { User o ->
return [
username: o.username,
firstName: o.firstName
]
}
})
}
def destroy = { }
}
這將註冊兩個命名marshallers,你可以在你的控制器(S)使用這樣的:
// UserController.groovy
package com.example
import grails.converters.JSON
class UserController {
def action1() {
def users = User.getAll()
JSON.use("userEmployeeView") {
render users as JSON
}
}
def action2() {
def users = User.getAll()
JSON.use("userOtherView") {
render users as JSON
}
}
}
以上使用名爲marshllers它允許你來控制創建最終的JSON輸出時將使用哪個JSON表示(實際上只是一個Map
)。
希望這會有所幫助,並且原諒任何錯別字,因爲我從頭頂寫下了這個錯誤。
你在試圖做什麼?爲什麼每個控制器操作需要一個?你有什麼嘗試?什麼不是在嘗試你所嘗試的? – 2015-01-21 11:53:23
爲什麼你不只是返回一個地圖的內容? – cfrick 2015-01-21 13:26:12
@cfrick謝謝編輯... – 2015-01-22 12:14:25