2011-11-17 3 views
1

this post에서 찾은 사용자 정의 형식화 날짜와 비슷한 Grails JSON 변환을 통해 문자열 형식을 지정하는 방법을 찾고 있습니다. 이 같은Grails JSON marshaller의 사용자 정의 문자열 형식

뭔가 :

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) 

을 내 예를 들어 나는 단지 SCIP '메타 클래스'와 '클래스의 필드에. 가장 일반적인 방법이라고 생각합니다

+0

잘 작동 했어, 고마워! – ethaler