3

I'm working with a JSON file, and I need to transform it into an object. Everything seems easy so far, but I found a problem trying to parse dates.

I'm trying to do something like this:

//My JSON file
data={
    "title":"myTitle"
    "releaseDate":"2012-05-28"
}

//Myclass
class Book{
String title
Date date
}

Book book = JSON.parse(data)

And I receive an error:

Cannot cast object  with class 'org.codehaus.groovy.grails.web.json.JSONObject' to class 'Book' due to: 
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '2012-05-28' with class 'java.lang.String' to class 'java.util.Date'

I think I know why is this happening (Obviously, I can't cast a String into a Date) but I've no idea how to fix it.

I've also tried to define in Config.groovy my format date, like this:

grails.converters.json.date = 'yyyy-MM-dd'
Sébastien Le Callonnec
  • 26,254
  • 8
  • 67
  • 80
elcadro
  • 1,482
  • 3
  • 21
  • 45
  • 1
    this seems like a duplicate of [Grails date unmarshalling](http://stackoverflow.com/questions/963922/grails-date-unmarshalling/964083#964083) – Alonso Dominguez May 28 '12 at 14:55
  • I already saw this post, but that solution is not working for me. Any other ideas? Thanks! – elcadro May 28 '12 at 15:37

1 Answers1

3

That is a quite discussed topic recently. Recent GRAILS version, say 3.x, has powerful simple support. See for example this answer.
Briefly, you have to insert in application.yml or in application.groovy a list of general formats to clarify conversion into Date from String. For example in application.groovy:

grails.databinding.dateFormats = ["yyyy-MM-dd'T'hh:mm:ss.S'Z'", 'ddMMyyyy', 'yyyy-MM-dd HH:mm:ss']

and in this way if you have a domain Book.groovy with a Date property

def book = new Book(JSON.parse(stringJson))

will work perfectly. Tested with GRAILS 3.1.6.

Community
  • 1
  • 1