我最近需要做类似的事情。一些注意事项:
- 这是使用Grails 2.4.5
- 我使用MongoDB的作为后端。就这样,我为MongoDB域类创建了一个对象编组器。它低于打印,你可以用一个类似的编组为您的域类(ES):
的Marshaller:
class MongodbObjectMarshaller implements ObjectMarshaller<JSON> {
@Override
boolean supports(Object o) { return o?.properties?.dbo }
@Override
void marshalObject(Object obj, JSON converter) throws
ConverterException {
Map propertiesToOutput = obj.properties.dbo
propertiesToOutput.remove("_id") //don't print org.bson.types.ObjectId
propertiesToOutput.remove("version") //don't print gorm verson column
converter.build {
_id obj.id.toString()
propertiesToOutput.each{ entry ->
"$entry.key" entry.value
}
}
}
}
什么是编组呢,它在JSON输出允许任何领域类的的属性。 obj.properties.dbo
对于MongoDB来说是特殊的,但对于一个普通的域类,你可以获取属性并排除你不需要的属性。
然后在我的控制器,这个工程:
domainInstance.pin = [location:[lat:23.03, lon:72.58]]
def content = tacticalCard as JSON
,因为我现在编组拿起针财产并打印。
这将添加引脚作为域实例的一部分吗? – Sap
不,它不会。但是你真的需要将你的域名与其他域名合并吗?如果是这样,也许将这个字段添加到您的域类会更好?或者在其中创建一个代理字段,为'pin'提供一个getter? –
这是我的第一次尝试,我在域类中添加了lat和lon,并创建了'public getPin(){'方法,但是当我做'对象为JSON'引脚不会出现在JSON的字符串表示中 – Sap