Grails 持久化日期并用JSON嵌套

Grails 持久化日期并用JSON嵌套,grails,Grails,我试图保存嵌套的person,它是json数组,并抱怨需要一个集合 我遇到的另一个问题是,另一个字段日期不能为null,但已包含值 在将参数添加到对象之前,我需要做什么,或者我必须更改json的构建?我正试图像这样保存json帖子: // relationship of Test //static hasMany = [people: Person, samples: Sample] def jsonParams= JSON.parse(request.JSON.toString()) def

我试图保存嵌套的person,它是json数组,并抱怨需要一个集合

我遇到的另一个问题是,另一个字段日期不能为null,但已包含值

在将参数添加到对象之前,我需要做什么,或者我必须更改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"
], //...

首先,这一行是不必要的:

def jsonParams= JSON.parse(request.JSON.toString())
request.JSON
可以直接传递给
Test
构造函数:

def testInstance = new Test(request.JSON)

我不确定您的
Person
类是什么样子,但我假设这些数字(1137141)是ID。如果是这样,那么您的json应该可以工作——直接传递
请求.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.S
yyyy-MM-dd'T'HH:MM:ss'Z'
,但这些格式可以由
grails.databinding.dateFormats
配置设置(
config.groovy
)定义。还有其他方法可以进行绑定(
@BindingFormat
注释),但以grails无需额外配置即可处理的方式发送日期将是最简单的

如果您死心塌地地想要将
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]
,并对内部集合使用了两种语法(JSON数组和索引键)。我个人会坚持使用一种语法来清理它:

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

哦,我不知道我能做到