【问题标题】:Grails bindData doesn't match nested objects after upgrade to 2.4.4升级到 2.4.4 后 Grails bindData 不匹配嵌套对象
【发布时间】:2015-01-15 23:07:23
【问题描述】:

我最近将一个项目从 2.1.0 升级到 Grails 2.4.4

在很多地方,我们使用 bindData 将传入的 JSON 映射到域对象,包括嵌套对象。升级或符号更改后,这似乎不起作用。

例如

Class Book {
   Author author
   ...
}

传入 JSON

{ "author.id" : 7 }  

然后打电话

def book = new Book()
bindData(book, request.JSON, [include: ['author']])

以前会找到作者 7 并将他附加到示例书中。现在它不绑定任何东西。有没有其他人遇到过这个问题或类似的问题?

谢谢

编辑:

更新传入的 JSON 可解决此问题,并且是一种潜在的解决方法:

{ "author" : { "id" : 7 } } 

这种格式更有意义,但不幸的是,它一开始并不是这样构建的。

【问题讨论】:

  • 向我们展示Book的观点也很重要。

标签: json grails


【解决方案1】:

这可能会对您有所帮助。
出于某种原因,我不能使用默认的数据绑定器,所以我想出了这个自定义数据绑定器。

Object bindDataCustom (Object targetObject, Map sourceObject) { //named bindDataCustom so it cant confuse with bindData
        sourceObject.each{ property, value->
            if(property.toString().contains(".")){
                String[] nestedProperty = property.toString().split("\\."); //e.g split author.id to author and id
                String subObjectName = nestedProperty[0][0].toUpperCase() + nestedProperty[0].substring(1)
                String subObjectPropertyName = nestedProperty[1]

                Object subObject = Class.forName(packageName + subObjectName, true, Thread.currentThread().getContextClassLoader())."findBy${subObjectPropertyName[0].toUpperCase()}${subObjectPropertyName.substring(1)}"(value)

                targetObject."${nestedProperty[0]}" = subObject

            }else{
                DataBindingUtils.bindObjectToInstance(targetObject, sourceObject, [property], [], null)
            }
        }

        return targetObject;
    }

现在你可以这样做了:

def book = new Book()
bindDataCustom(book, request.JSON)

【讨论】:

  • 如果我不能让它以旧方式工作,这是一个潜在的解决方法。谢谢。
猜你喜欢
  • 2014-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-16
相关资源
最近更新 更多