2014-01-13 46 views
1

我在Grails项目中有这样的控制器:Grails领域构造没有工作

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这样的错误:在对象

  • 场误差现场“com.entity.Share”“设备名称”:拒绝值[空]
  • 字段'originMessage'上的对象'com.entity.Share'中的字段错误:rejected value [null];代码

大量的跳舞找到一种可能的方式:在控制器中将JSON转换为字符串并将其传递给构造函数,其中参数将是String类型,然后使用JSON转换器将其解析为JSON。但为什么我无法正确传递JSON对象作为参数。怎么了?

+1

删除你的构造,并再次尝试空。 Grails已经有了这样的领域类的构造函数。 –

+0

是的,我知道,但我不喜欢构造函数的映射风格。然而,为什么我看到这样奇怪的行为? – sphinks

回答

2

我没有在声明这个构造函数时看到太多的观点,因为域类已经有一个隐含的构造函数,它的参数为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实例没有命名deviceNameoriginMessage非空的属性。

要么你需要弄清楚为什么这些属性缺失,或允许这些属性中加入以下约束域类

class Share { 

    String timestamp 
    String deviceName 
    String originMessage 

    static constraints = { 
     deviceName nullable: true 
     originMessage nullable: true 
    } 
} 
+0

是的,我知道groovy中的默认构造函数。使用JSON有用的地图样式,但正如你可以看到originalMessage不只是字段,而是原始的JSON请求。当然,我仍然可以使用Map构造器枚举所有带有值的字段,但我也不喜欢Map风格,这就是为什么我创建了自己的构造器。关于错误的消息,是的,我看到它对我说的话和我的问题关于完全相同的原因为什么这种属性在这种情况下失踪,并在字符串的情况下工作完美? – sphinks