我正在尝试像这样注册一个自定义 json marshaller
JSON.createNamedConfig("dynamic",{
def m = new CustomJSONSerializer()
JSON.registerObjectMarshaller(Idf, 1, { instance, converter -> m.marshalObject(instance, converter) })
})
and then using it like this
JSON.use("dynamic"){
render inventionList as JSON
}
但我不确定是否正在使用我的自定义序列化程序,因为当我调试控件时marshalObject
,我的自定义序列化程序永远不会发挥作用
我的自定义序列化程序如下
import grails.converters.deep.JSON
import java.beans.PropertyDescriptor
import java.lang.reflect.Field
import java.lang.reflect.Method
import org.codehaus.groovy.grails.web.converters.exceptions.ConverterException
import org.codehaus.groovy.grails.web.converters.marshaller.json.GroovyBeanMarshaller
import org.codehaus.groovy.grails.web.json.JSONWriter
class CustomJSONSerializer extends GroovyBeanMarshaller{
public boolean supports(Object object) {
return object instanceof GroovyObject;
}
public void marshalObject(Object o, JSON json) throws ConverterException {
JSONWriter writer = json.getWriter();
println 'properties '+BeanUtils.getPropertyDescriptors(o.getClass())
for(PropertyDescriptor property:BeanUtils.getProperyDescriptors(o.getClass())){
println 'property '+property.getName()
}
try {
writer.object();
for (PropertyDescriptor property : BeanUtils.getPropertyDescriptors(o.getClass())) {
String name = property.getName();
Method readMethod = property.getReadMethod();
if (readMethod != null && !(name.equals("metaClass")) && readMethod.getName()!='getSpringSecurityService') {
Object value = readMethod.invoke(o, (Object[]) null);
writer.key(name);
json.convertAnother(value);
}
}
for (Field field : o.getClass().getDeclaredFields()) {
int modifiers = field.getModifiers();
if (Modifier.isPublic(modifiers) && !(Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers))) {
writer.key(field.getName());
json.convertAnother(field.get(o));
}
}
writer.endObject();
}
catch (ConverterException ce) {
throw ce;
}
catch (Exception e) {
throw new ConverterException("Error converting Bean with class " + o.getClass().getName(), e);
}
}
}
是否可以调试序列化程序?如果不是,那么如何从序列化中排除属性?有一些属性会在序列化过程中引发异常。