2014-08-28 78 views
0

我不明白在控制器(不是RESTController,而是經典控制器)中將對象呈現爲JSON時,如何排除某些屬性。 我有這個resources.groovy:在grails中將對象渲染爲json時排除屬性2.4.0

// Place your Spring DSL code here 
import grails.rest.render.json.JsonRenderer 
import com.appromocodes.Promocode 
import com.appromocodes.ResponseStatus 
import grails.rest.render.json.JsonCollectionRenderer 

beans = { 
    responseStatusRenderer(JsonRenderer, ResponseStatus) { 
     excludes = ['enumType'] 
    } 

    promocodeRenderer(JsonRenderer, Promocode) { 
     excludes = ['class', 'id', 'project'] 
    } 

} 

在我的控制器,我在行動類似的嘗試:

respond p as JSON 

但這仍然給我所有的字段(也一流,ID和策劃領域) 。

我該怎麼辦?

+0

爲什麼'作爲對象'而不是'作爲JSON'? – rmlan 2014-08-28 17:14:27

+0

對不起,我做了一個類型,現在我改變了「作爲JSON」(這是來自各種嘗試的錯字),但結果總是相同的:我總是顯示類屬性 – 2014-08-29 16:45:20

回答

1

處理此問題的正確方法是爲您的對象註冊自定義JSON編組器。在src/groovy/packageName/marshallers/PromocodeMarshaller.groovy使用以下內容創建一個新的Marshaller開始:

import packageName.Promocode 
import grails.converters.JSON 

class PromocodeMarshaller { 

    void register() { 
    JSON.registerObjectMarshaller(Promocode) { promocode -> 
     return [ 
     id: promocode?.id, 
     // all the fields you'd like to return 
     // in your JSON object 
     ] 
    } 
    } 
} 

然後,你Bootstrap.groovy文件裏面,包括以下內容:

import packageName.marshallers.PromocodeMarshaller 

def promodcodeMarshaller = new PromocodeMarshaller() 
promocodeMarshaller.register() 

有關詳細說明,請參見this article