1

この投稿で見つけたカスタム形式の日付と同様に、Grails JSON 変換を使用して文字列形式を設定する方法を探しています。

このようなもの:

import grails.converters.JSON;

class BootStrap {

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

ドメイン クラスごとにカスタム フォーマットを実行できることは知っていますが、よりグローバルなソリューションを探しています。

4

1 に答える 1

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)

私の例では、「metaClass」フィールドと「class」フィールドをscipします。私は最も一般的な方法だと思います

于 2011-11-18T17:48:42.740 に答える