Custom string formatting in Grails JSON marshaller

你说的曾经没有我的故事 提交于 2019-12-06 15:49:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!