我的grails项目中有这样的 Controller :
def submit() {
def json = request.JSON
Share share = new Share(json)
share.save(flush: true, failOnError: true)
}
类共享看起来像这样:
class Share {
String timestamp
String deviceName
String originMessage
Share(JSONObject originalMessage) {
println "Run JSON constructor"
println "$originalMessage"
originMessage = originalMessage.toString()
timestamp = originalMessage.timestamp
deviceName = originalMessage.device
}
它接收JSON请求并尝试保留在数据库中。
我在failOnError的控制台中收到这样的错误:
很多方法都找到了一种可能的方法:在 Controller 中,将JSON转换为字符串,然后将其传递到参数为String类型的构造函数中,然后使用JSON转换器将其解析回JSON。但是为什么我不能正确地将JSON对象作为参数传递。怎么了?
最佳答案
在声明此构造函数方面,我没有多大意义,因为域类已经具有使用Map
参数的隐式构造函数。您可以使用JSONObject
调用此构造函数,因为此类实现了Map
,例如
class Share {
String timestamp
String deviceName
String originMessage
}
def json = request.JSON
Share share = new Share(json)
这些错误的原因
Field error in object 'com.entity.Share' on field 'deviceName': rejected value [null];
Field error in object 'com.entity.Share' on field 'originMessage': rejected value [null]; codes
是您的
JSONObject
实例没有名为deviceName
或originMessage
的非null属性。您需要弄清楚为什么缺少这些属性,或者通过向域类中添加以下约束来允许这些属性为空
class Share {
String timestamp
String deviceName
String originMessage
static constraints = {
deviceName nullable: true
originMessage nullable: true
}
}
关于json - 带有JSON参数的Grails域构造函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21100478/