evanwong
evanwong

Reputation: 5134

Grails GORM date databinding

I am using Grails 2.3 and I have a domain with a date field:

class DomainClass {
    String title
    Date datetime
} 

And I have a json coming in to the RestfulController with timestamp in milliseconds:

{"title": "name", "datetime": 957044075522}

The controller is binding the title correctly but for the datetime field, it is actually an error:

Could not find matching constructor for: java.util.Date(com.google.gson.internal.LazilyParsedNumber)

What's the best way to fix this?

Thanks.

Upvotes: 1

Views: 2631

Answers (3)

Brian F
Brian F

Reputation: 1660

I would recommend against sending milliseconds as you are losing the timezone information.

If that's not an issue for you and want to go ahead as is I would just recommend using a command object in your controller which parses it as a string and then do a custom binding.

class DomainCmd {
   String title
   String datetime

   static constraints = {
       datetime matches: /[0-9]{12}/
   } 
}

Then in the controller;

myControllerAction(DomainCmd cmd) {
   if (cmd.validate()) {
       def myDomain = new DomainClass(title: cmd.title, datetime: new Date(cmd.datetime))
       // 
   } else {
      // HTTP ERROR 
      response.status = 400
   }
}

(also consider using joda time instead of java dates)

Upvotes: 1

evanwong
evanwong

Reputation: 5134

Both of the Brain F and zoran119 answers make sense so I voted them up. If anyone is doing the same thing, this is the actual answer that works:

@BindUsing({ obj, source -> source['datetime']?.longValue() })
Date datetime

Upvotes: 1

zoran119
zoran119

Reputation: 11327

I would try using @BindingFormat annotation:

import org.grails.databinding.BindingFormat

class DomainClass {
    String title
    @BindingFormat('MMddyyyy')
    Date datetime
}

You need to replace MMddyyyy to something which will work for you...

Upvotes: 2

Related Questions