2011-11-17 29 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