【问题标题】:Custom string formatting in Grails JSON marshallerGrails JSON 编组器中的自定义字符串格式
【发布时间】:2011-12-31 19:06:06
【问题描述】:

我正在寻找一种通过 Grails JSON 转换进行字符串格式化的方法,类似于我在 this post 中找到的自定义格式化日期。

类似这样的:

import grails.converters.JSON;

class BootStrap {

     def init = { servletContext ->
         JSON.registerObjectMarshaller(String) {
            return it?.trim()             }
     }
     def destroy = {
     }
}

我知道自定义格式可以在每个域类的基础上完成,但我正在寻找一个更全球化的解决方案。

【问题讨论】:

  • 不确定您所说的“更全球化的解决方案”是什么意思
  • 我希望能够让一个闭包负责所有类的字符串自定义,而不是遍历 X 个域类并为每个类编写一个编组器。

标签: json grails groovy marshalling converters


【解决方案1】:

尝试创建对属性名称或类使用特定格式的自定义编组器。看看下面的 marshaller 并修改它:

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)

在我的示例中,我只是 scip 'metaClass' 和 'class' 字段。我认为最常见的方式

【讨论】:

    猜你喜欢
    • 2012-08-28
    • 1970-01-01
    • 2017-09-07
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多