Tôi cố gắng để đăng ký một marshaller tùy chỉnh json như thế nàylàm thế nào để đăng ký một marshaller json tùy chỉnh trong grails
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
}
nhưng tôi không chắc chắn nếu serializer tùy chỉnh của tôi đang được sử dụng bởi vì khi tôi gỡ lỗi kiểm soát không bao giờ đi vào marshalObject
chức năng của serializer tùy chỉnh của tôi
serializer tùy chỉnh của tôi là như sau
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);
}
}
}
có thể gỡ lỗi s erializer? Nếu không thì làm thế nào tôi có thể loại trừ một tài sản từ serialization? Có một số tài sản mà ném ngoại lệ trong quá trình serialization.
tôi giải quyết nó bằng cách nhập vài file đã mất như BeanUtils và Modifier –