的JSON排除的Marshaller插件
我最近需要解决这个问题。我继续将解决方案打包到一个插件中,该插件允许您轻松地从JSON转换器的输出中排除类属性。它可以在Grails插件门户上找到。
在install the plugin之后,您将有权访问名为excludeFor *()的grails.converters.JSON类上的方法。
更广泛的文档可以在这里找到:How to use the JSON Exclusion Marshaller
但基本上可以作为这样的:
import grails.converters.JSON
def json, resultTeachersWillSee, resultOtherStudentsWillSee
// Given a TestStudent Domain Class
def student = new TestStudent([
firstName: "Tobias",
lastName: "Funke",
gradePointAverage: 3.6,
studentID: "FS-210-7312",
socialSecurityNumber: "555-55-5555"
])
student.save(flush: true)
// When
JSON.excludeForTeachers(TestStudent, ['socialSecurityNumber', 'id', 'class'])
JSON.use('excludeForTeachers') {
json = new JSON(student)
}
resultTeachersWillSee = json.toString()
// Then
assert resultTeachersWillSee == '{"firstName":"Tobias",
"gradePointAverage":3.6, "lastName":"Funke",
"studentID":"FS-210-7312"}'
// And When
JSON.excludeForOtherStudents(TestStudent, ['gradePointAverage', 'studentID',
'socialSecurityNumber', 'id', 'class'])
JSON.use('excludeForOtherStudents') {
json = new JSON(student)
}
resultOtherStudentsWillSee = json.toString()
// Then
assert resultOtherStudentsWillSee == '{"firstName":"Tobias",
"lastName":"Funke"}'
JSON.excludeForTeachers(...)创建了一个名为 “excludeForTeachers” 命名对象编组。编组器从生成的JSON输出中排除学生对象的三个属性。 'socialSecurityNumber'属性在类中显式定义,而'id'属性在后台被GORM添加。无论如何,教师不需要看到任何这些属性。
该插件正在为我服务......我希望别人也发现它也有帮助。
Gregg它的工作原理,但我想除了属性,因为我有几个域类,可以需要20个以上的属性,我想除了只有一个或two.If我没有找到其他的解决方案,除了我会用它...谢谢 – Bella 2011-05-10 11:06:32
很酷的东西!你救了我的一天) – 2014-06-30 12:46:53
@Gregg你认为或遇到性能问题时marshallers实施。我们在2个项目中使用了它们,并且我们体验了它们。有没有其他方法呢? – 2015-08-07 08:46:51