我的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的控制台中收到这样的错误:
  • 字段'deviceName'上的对象'com.entity.Share'中的字段错误:拒绝的值[null];
  • 字段'originMessage'上的对象'com.entity.Share'中的字段错误:拒绝的值[null];代码

  • 很多方法都找到了一种可能的方法:在 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实例没有名为 deviceNameoriginMessage的非null属性。

    您需要弄清楚为什么缺少这些属性,或者通过向域类中添加以下约束来允许这些属性为空
    class Share { 
     
        String timestamp 
        String deviceName 
        String originMessage 
     
        static constraints = { 
            deviceName nullable: true 
            originMessage nullable: true  
        } 
    } 
    


    评论关闭
    IT序号网

    微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!