2015-12-06 27 views
0

我試圖保存嵌套的人,這是json數組,並抱怨需要一個集。持久化日期和JSON嵌套

我遇到的另一個問題是,另一個字段日期不能爲空,但已包含值。

我需要做什麼之前添加PARAMS到我的對象或我必須改變我的JSON是建立?我試圖挽救JSON後是這樣的:

// relationship of Test 
//static hasMany = [people: Person, samples: Sample] 

def jsonParams= JSON.parse(request.JSON.toString()) 
def testInstance= new Test(jsonParams) 

//Error requiring a Set 
[Failed to convert property value of type 'org.codehaus.groovy.grails.web.json.JSONArray' to required type 'java.util.Set' for property 'people'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.Person] for property 'people[0]': no matching editors or conversion strategy found]] 
//error saying its null 
Field error in object 'com.Test' on field 'samples[2].dateTime': rejected value [null]; codes [com.Sample] 

//... 
"samples[0].dateTime_hour":"0", 
"samples[0].dateTime_minute":"0", 
"samples[0].dateTime_day":"1", 
"samples[0].dateTime_month":"0", 
"samples[0].dateTime_year":"-1899", 
"samples[0]":{ 
    "dateTime_minute":"0", 
    "dateTime_day":"1", 
    "dateTime_year":"-1899", 
    "dateTime_hour":"0", 
    "dateTime_month":"0" 
}, 
"people":[ 
    "1137", 
    "1141" 
], //... 

回答

0

首先,部份線路是不必要的:

def jsonParams= JSON.parse(request.JSON.toString()) 

request.JSON可以直接傳遞給Test構造:

def testInstance = new Test(request.JSON) 


我不確定你的 Person類是什麼樣的,但我假設這些數字(1137,1141)是ID。如果是這樣的話,那麼你的json應該工作 - 有可能直接通過 request.JSON可以提供幫助。我在本地測試了您的JSON,並且在關聯 hasMany集合時沒有任何問題。我也用過:

// JSON numbers rather than strings 
"people": [1137, 1141] 

// using Person map with the id 
"people: [{ 
    "id": 1137 
}, { 
    "id": 1141 
}] 

這兩種工作都很好,值得一試。


關於null dateTime,我會重做你的JSON。我會在單個字段中發送 dateTime,而不是將該值分成小時/分鐘/天/等等。默認格式爲 yyyy-MM-dd HH:mm:ss.Syyyy-MM-dd'T'hh:mm:ss'Z',但這些可以由 grails.databinding.dateFormats配置設置( config.groovy)定義。還有其他一些方法可以執行綁定( @BindingFormat註釋),但最簡單的方法是以不需要額外配置的方式發送日期。

如果你是在分裂dateTime成片死心塌地,那麼你可以使用@BindUsing註釋:

class Sample{ 
    @BindUsing({obj, source -> 
     def hour = source['dateTime_hour'] 
     def minute = source['dateTime_minute'] 
     ... 
     // set obj.dateTime based on these pieces 
    }) 
    Date dateTime 
} 


你的JSON額外的評論,你似乎有 samples[0]兩次定義和使用2內部集合的語法(JSON數組和索引鍵)。我個人會堅持使用單一的語法來清理它:

"samples": [ 
    {"dateTime": "1988-01-01..."} 
    {"dateTime": "2015-10-21..."} 
],"people": [ 
    {"id": "1137"}, 
    {"id": "1141"} 
], 
+0

哦,我不知道我可以 – fsi