在我当前的项目中,我很愚蠢地制作了一个期望变量私有(private)的 API。在 Controller 中它被映射到isPrivate,但现在我想创建一个commandObject(@validatable)来检查一切是否有效。如何在 isPrivate 上使用自动绑定(bind)映射私有(private)变量?
@Validateable
class EventCommand{
boolean isPrivate
boolean fullDay
String title
String location
String description
static constraints = {
location(nullable: true)
description(nullable: true)
fullDay (nullable: false)
isPrivate(nullable: false)
title (blank: true, nullable: false)
}
}
以及数据绑定(bind)发生的代码(在 grails Controller 内):
def add() {
def jsonData = request.JSON
EventCommand command = new EventCommand(jsonData)
if(!command.validate()){
throw new QuivrException(command)
}
boolean isPrivate = jsonData.private
//some things happen, uninmportant
}
我已经尝试过使用 @BindUsing 注释,但我总是收到 EventCommand 没有名为“private”的属性的错误(匹配有效,但他试图将私有(private)匹配到不存在的东西)
有什么方法可以解决这个问题而不将收到的私有(private)更改为 isPrivated(已经获得了旧版本的应用程序并且 20% 不是最新版本)
最佳答案
好吧,从您的 jsonData 中删除私有(private)属性,然后进行绑定(bind),并在绑定(bind)后从您应该获取私有(private)值的变量中手动添加私有(private)。
因此,您的添加可能类似于
def add() {
def jsonData = request.JSON
String isPrivate = jsonData.private
jsonData.remove("private")
EventCommand command = new EventCommand(jsonData)
if(!command.validate()){
throw new QuivrException(command)
}
command.isPrivate = isPrivate as Boolean
}
关于validation - grails 数据绑定(bind)参数 a 在 b 上的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36273605/