Grails转换器在实例上进行JSON编组
在Grails JSON Converters上下文中,希望转换作为MongoDB查询结果的JSON数据(结果没有关联的域对象) 其中一个字段需要转换(即,具有货币符号的字段需要通过剥离货币符号转换为数字) 在这种情况下,是否可以仅将封送拆收器应用于此实例数据 使用:Grails转换器在实例上进行JSON编组,json,mongodb,grails,groovy,marshalling,Json,Mongodb,Grails,Groovy,Marshalling,在Grails JSON Converters上下文中,希望转换作为MongoDB查询结果的JSON数据(结果没有关联的域对象) 其中一个字段需要转换(即,具有货币符号的字段需要通过剥离货币符号转换为数字) 在这种情况下,是否可以仅将封送拆收器应用于此实例数据 使用: JSON.registerObjectMarshaller(JSONObject) 全局应用于代码中所有其他位置的所有JSONObject 我不希望为此目的创建域对象,而是希望使用grails converter对象,如JSON
JSON.registerObjectMarshaller(JSONObject)
全局应用于代码中所有其他位置的所有JSONObject
我不希望为此目的创建域对象,而是希望使用grails converter对象,如JSONObject等。是的,您可以通过使用命名封送器轻松实现它。i、 e.在Bootstrap.groovy中使用相同的命名空间注册封送拆收器:
JSON.createNamedConfig("foo") {
it.registerObjectMarshaller(new CustomDataMarshaller)
}
马歇尔代码:
class CustomDataMarshaller implements ObjectMarshaller<JSON> {
@Override
boolean supports(Object object) {
return object instanceof Currency // Or directly BasicDbObject if you want to marshall the whole MongoDb result
}
@Override
void marshalObject(Object object, JSON converter) throws ConverterException {
// Convert here
}
}
class MyController {
def test() {
def data // Any data as you want to marshal
JSON.use("foo") {
respond(data)
// OR
// render(data as JSON)
}
}
}