我知道在grails中我可以定义不同的JSON marshallers并为它们设置不同的用途名称,这非常好。然而,我在Bootstrap部分结束了很多代码,并且结束了两个我需要调整域类更改时的地方。Grails类域中的JSON marshallers
Ithink thi不够好,我不知道是否可以在域类本身中定义JSON marshallers。
你认为这是一个很好的做法吗? ...你能提供一些建议来达到这个目标吗?
感谢,
我知道在grails中我可以定义不同的JSON marshallers并为它们设置不同的用途名称,这非常好。然而,我在Bootstrap部分结束了很多代码,并且结束了两个我需要调整域类更改时的地方。Grails类域中的JSON marshallers
Ithink thi不够好,我不知道是否可以在域类本身中定义JSON marshallers。
你认为这是一个很好的做法吗? ...你能提供一些建议来达到这个目标吗?
感谢,
BootStrap.groovy中编写代码:
JSON.registerObjectMarshaller(YourClass) { YourClass yourClass->
Map result = [:]
result['yourClass.property'] = yourClass.property
def domain = new DefaultGrailsDomainClass(YourClass)
domain.persistentProperties.each { GrailsDomainClassProperty property, String propertyName = property.name ->
result[propertyName] = yourClass[(propertyName)]
}
return result
}
代码下面添加一个属性,你可以将其命名如何ü希望
result['yourClass.property'] = yourClass.property
该代码添加由它的名字的所有属性映射:
domain.persistentProperties.each { GrailsDomainClassProperty property, String propertyName = property.name ->
result[propertyName] = yourClass[(propertyName)]
}
什么是“事件[propertyName”中的事件? – Kachwahed 2016-03-30 15:17:03
@Kachwahed是的,有错误。应该是yourClass [(propertyName)] – Koloritnij 2016-03-31 20:41:54
我写了用于此目的的专门plugin。它可以让你在领域类使用注释,像这样:
import grails.plugins.jsonapis.JsonApi
class User {
static hasMany = [
pets: Pet
]
@JsonApi
String screenName
@JsonApi('userSettings')
String email
@JsonApi(['userSettings', 'detailedInformation', 'social'])
String twitterUsername
@JsonApi(['detailedInformation', 'userSettings'])
Set pets
String neverGetsSerialized
@JsonApi('detailedInformation')
Integer getNumberOfTicklyAnimals() {
pets.count { it.likesTickling }
}
}
在你的控制,你会再调用激活特定的编组。
mmm ...对我来说很好看! ...也许这个名字可以改进,但看起来很有趣 – Rafael 2014-12-04 11:59:21
»计算机科学中只有两件难事:缓存失效和命名事物。 «;) – 2014-12-04 12:02:16
这完全取决于你如何管理你的代码。我通常会为Marshallers创建一个MarshallerBootstrap.groovy。这里还有另一个想法:http://compiledammit.com/2012/08/16/custom-json-marshalling-in-grails-done-right/ – 2014-12-04 11:17:15