嘗試創建對屬性名稱或類使用特定格式的自定義編組器。試想一下,在編組波紋管,並修改它:
class CustomDtoObjectMarshaller implements ObjectMarshaller<JSON>{
String[] excludedProperties=['metaClass']
public boolean supports(Object object) {
return object instanceof GroovyObject;
}
public void marshalObject(Object o, JSON json) throws ConverterException {
JSONWriter writer = json.getWriter();
try {
writer.object();
for (PropertyDescriptor property : BeanUtils.getPropertyDescriptors(o.getClass())) {
String name = property.getName();
Method readMethod = property.getReadMethod();
if (readMethod != null && !(name in excludedProperties)) {
Object value = readMethod.invoke(o, (Object[]) null);
if (value!=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);
}
}
}
在引導寄存器:
CustomDtoObjectMarshaller customDtoObjectMarshaller=new CustomDtoObjectMarshaller()
customDtoObjectMarshaller.excludedProperties=['metaClass','class']
JSON.registerObjectMarshaller(customDtoObjectMarshaller)
在我的例子我只是上海化學工業區的元類「和「類」字段。我認爲最常見的方法
不確定你的意思是_「一個更全面的解決方案」_ –
我希望能夠有一個閉包管理所有類的字符串定製,而不是通過X數字域類併爲每個編寫一個編組。 – ethaler