2011-11-17 30 views
1

我正在寻找一种通过Grails JSON转换来完成字符串格式设置的方法,类似于我在this post中找到的自定义格式设置日期。Grails中的自定义字符串格式JSON编组

事情是这样的:

import grails.converters.JSON; 

class BootStrap { 

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

我知道自定义格式可以在每个领域类的基础上进行的,但我要寻找一个更具全球性的解决方案。

+2

不确定你的意思是_“一个更全面的解决方案”_ –

+0

我希望能够有一个闭包管理所有类的字符串定制,而不是通过X数字域类并为每个编写一个编组。 – ethaler

回答

6

尝试创建对属性名称或类使用特定格式的自定义编组器。试想一下,在编组波纹管,并修改它:

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) 

在我的例子我只是上海化学工业区的元类“和“类”字段。我认为最常见的方法

+0

工作得很好,谢谢! – ethaler