问题
I am looking for a way to do some string formatting through Grails JSON conversion, similar to custom formatting dates, which I found in this post.
Something like this:
import grails.converters.JSON;
class BootStrap {
def init = { servletContext ->
JSON.registerObjectMarshaller(String) {
return it?.trim() }
}
def destroy = {
}
}
I know custom formatting can be done on a per domain class basis, but I am looking for a more global solution.
回答1:
Try to create custom marshaller that use specific formatting for property names or class. Just look at the marshaller bellow and modify it:
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);
}
}
}
The register in bootstrap:
CustomDtoObjectMarshaller customDtoObjectMarshaller=new CustomDtoObjectMarshaller()
customDtoObjectMarshaller.excludedProperties=['metaClass','class']
JSON.registerObjectMarshaller(customDtoObjectMarshaller)
In my example I just scip 'metaClass' and 'class' fields. I think the most common way
来源:https://stackoverflow.com/questions/8175286/custom-string-formatting-in-grails-json-marshaller