2014-07-04 162 views
1

我使用Grails 2.3.8。我注意到Grails JSON呈現中的奇怪行爲。我有一個域類ShiftUpdateResponse映射到mongodb,如下所示。Grails JSON渲染

 class ShiftUpdateResponse { 
     List<Employee> employees 
     SalesPersonHours salesPersonHours; 
     Integer fromDate 
     Integer toDate 
     Integer success 

     static mapWith = "mongo" 
     static hasMany = [employees:Employee] 
     static embedded = ['employees','salesPersonHours'] 
     static constraints = { 
      salesPersonHours nullable:true 
      success nullable:true 
      fromDate nullable:true 
      toDate nullable:true 
     } 

     String toString() { 
      " $employees" 
     } 
     } 

當我在我的控制器創建一個ShiftUpdateResponse對象,並使用下面的代碼片段呈現爲JSON:

def sur = new ShiftUpdateResponse(employees:[], salesPersonHours:[], success:1, fromDate:from, toDate:to) 
    println "from " + from 
    println "to " + to 
    println "from sur " + sur.fromDate 
    println "to sur " + sur.toDate 
    JSON.use('deep') 
    render sur as JSON 

我發現下面的東西

  • 當我不救在渲染之前創建的實例sur,控制檯輸出爲

    from 20130624 
    to 20130623 
    from sur null 
    to sur null 
    
  • 當我渲染之前保存創建的實例,控制檯輸出

    from 20130624 
    to 20130623 
    from sur null 
    to sur 20130623 
    

在這兩種情況下,呈現的JSON不包含的字段fromDatetoDate。可能是什麼原因 ? (我不需要這個實例被持久化,我只需要它被渲染爲JSON)。

編輯:

的JSON呈現的樣子:

{ 
"class": "com.scheduling.json.week.graphicalMode.ShiftUpdateResponse", 
"id": 37, 
"employees": [], 
"salesPersonHours": null, 
"success": 1 
    } 

控制器代碼:

@Transactional 
    def updateShift(){ 

    def reqJson = request.JSON 
    somService.updateShift(reqJson) 


    def from 
    def to 
    def week = WeekJson.get(reqJson.week_id) 

    // code to construct from and to from week 

    def sur = new ShiftUpdateResponse(employees:[],salesPersonHours:[],success:1,fromDate:from,toDate:to) 

    //sur.save(flush:true) 

    println "from "+from 
    println "to "+to 
    println "from sur "+sur.fromDate 
    println "to sur "+sur.toDate 


    JSON.use('deep') 
    render sur as JSON 

} 
+0

如何顯示呈現的JSON?顯示完整的控制器動作 –

+0

@JamesKleeh我添加了JSON和控制器的框架 – mostlyHarmless

回答

0

對不起,小白的錯誤。問題可能是因爲在不同的包中存在另一個相同文件的副本。刪除重複的固定事項。