grails数据绑定参数b上的映射

时间:2016-03-29 00:50:45

标签: validation grails data-binding nullable

在我目前的项目中,我制作一个期望变量私有的API是如此愚蠢。在控制器中它被映射到isPrivate,但现在我想创建一个commandObject(@validatable)来检查一切是否有效。如何在isPrivate上使用自动绑定映射私有变量?

@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)
    }
}

和数据绑定发生的代码(在grails控制器内):

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" (比赛有效,但他试图将私人比赛与不存在的比赛相匹配)

有没有办法解决这个问题而不将收到的私有更改为isPrivated(已经有旧版本的应用程序,并且20%没有更新版本)

1 个答案:

答案 0 :(得分:0)

从你的jsonData中删除私有属性,然后进行绑定,并在绑定后从一个你应该获取私有值的变量手动添加私有。

因此您的添加可能类似于

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
}