Feras Odeh
Feras Odeh

Reputation: 9296

Grails Data Binding Failed for Date Field

I want to bind domain class with nested domain objects to request.JSON data. It works fine except for a field of type Date in nested domain class it always gives null. Here is request.json

[..., cardInfo:[expiryDate:2016-07-21, ccv:3455, cardNumber:4111111111111111], ....]

I tried to bind these json using multiple ways:

 MyClass myClass=new MyClass(request.JSON)

And

myClass.properties=request.JSON    
bindData(myClass,request.JSON)
bindData(myClass.cardInfo,request.JSON.cardInfo)

Nothing worked for binding expiryDate. Is this a bug or there is something wrong I'm doing?

UPDATE:

I'm using Grails 2.4.2 . I also have this line included in my config file

grails.databinding.dateFormats = ['dd-MM-yyyy','MM-dd-yyyy','yyyy-MM-dd', 'yyyy-MM-dd HH:mm:ss.S']

Upvotes: 0

Views: 2176

Answers (2)

Dustin
Dustin

Reputation: 764

I think there are two problems here:

  1. Your JSON should have the date value in quotes (i.e. expiryDate: "2016-07-21"). Without quotes, it's probably binding only the beginning numeric part (2016), which is not one of your configured formats.
  2. There appears to be a Grails bug (we're on 2.5.0) with binding dates in nested domain classes (which is why I'm here). If you bind it properly (meaning, the date's format matches a format defined in grails.databinding.dateFormats), the date attribute is set fine. However, if there's a mismatch (meaning, the value is "2016" but the config is 'yyyy-MM-dd', the bad value is silently discarded without a validation error. I've seen this behavior with both embedded nested classes and in a belongsTo relationship, and I think that's why your expiryDate remains null.

Upvotes: 0

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27220

You haven't provided enough information to know for sure but I expect that the binder isn't configured to know about your date format. You can try something like this:

class MyClass {
    @org.grails.databinding.BindingFormat('yyyy-MM-dd')
    Date expiryDate
}

You can also configure that as a default date format in Config.groovy:

// grails-app/conf/Config.groovy
grails.databinding.dateFormats = ['yyyy-MM-dd', 'MMddyyyy', 'yyyy-MM-dd HH:mm:ss.S', "yyyy-MM-dd'T'hh:mm:ss'Z'"]

See http://grails.org/doc/latest/guide/theWebLayer.html#dataBinding for more details.

I hope that helps.

Upvotes: 1

Related Questions