的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