Sel*_*thu -1 grails groovy json
在 grails 中,如何为控制器中的每个操作使用 JSON.registerObjectMarshaller。
这是一个例子
我的User
域对象:
String username
String empId
String attendanceID
String password
String firstName
Run Code Online (Sandbox Code Playgroud)
在我的控制器中:
def myaction1() {
def user=User.getAll()
// XXX here i want to return just username and empId
render user as JSON
}
def myaction2() {
def user=User.getAll()
// XXX here i want to return just username and firstName
render user as JSON
}
Run Code Online (Sandbox Code Playgroud)
虽然对于简单的域来说这可能有点矫枉过正,而且您可能只需返回部分Map
数据就可以逃脱惩罚,但这个问题仍然有效。
如何注册自定义命名的编组器?
通常,您将在您的文件中执行此操作(如果您想保持干净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 = { }
}
Run Code Online (Sandbox Code Playgroud)
这将注册两个命名编组器,您可以在控制器中使用它们,如下所示:
// 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
}
}
}
Run Code Online (Sandbox Code Playgroud)
上面使用了命名的 marshllers,它允许您控制Map
在创建最终 JSON 输出时使用哪种 JSON 表示形式(实际上只是一个 )。
希望这会有所帮助,并原谅我随手写下的任何拼写错误。
归档时间: |
|
查看次数: |
1319 次 |
最近记录: |