JSON Marshaller用于控制器中的每个动作(Grails)

时间:2015-01-21 11:47:43

标签: json grails groovy

在grails中如何为控制器中的每个操作使用JSON.registerObjectMarshaller。

这是一个例子

我的User域对象:

String username
String empId
String attendanceID
String password
String firstName

在我的控制器中:

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
}

1 个答案:

答案 0 :(得分:4)

虽然对于简单的域名来说可能有些过分,但您可能只是返回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,你可以在你的控制器中使用这样的:

// 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)。

希望这会有所帮助,并且可以原谅任何错别字,因为我写下了这句话。