1
votes

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.

3
You might need to pass it as string with in a date format or implement custom data bindingEmmanuel John

3 Answers

2
votes

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...

1
votes

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
1
votes

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)