grails-gson icon indicating copy to clipboard operation
grails-gson copied to clipboard

Using an id that can be bindable will throw java.lang.NumberFormatException

Open sergiomichels opened this issue 11 years ago • 1 comments

When using parseRequest:true in UrlMappings the GSON.parse() method is parsing the id as a Double, causing problems when you create the instance from the params map and your domain class can have the id bindable (I need this for legacy databases).

class MyDomainClass {
  String descr

  static constraints = {
    id bindable: true, generator: 'assigned'
  }

}

JSON POST
{"id":77,"desc":"Test"}

MyDomainClass domain = new MyDomainClass(params) //java.lang.NumberFormatException

It would be nice to convert the id to the Long, or his declared type, instead of using Google's default.

I also tried creating the instance from request.GSON, but it returns null (still don't figured out why).

sergiomichels avatar Aug 02 '13 18:08 sergiomichels

I also tried creating the instance from request.GSON, but it returns null (still don't figured out why).

This might be due to the following:

If a JSON object contains an id property then it will use GORM to retrieve an existing instance, otherwise it creates a new one.

As a result, the deserialzer (GrailsDomainSerializer.groovy from the plugin) doesn't work well for domains that have 'assigned' ids. As a workaround, you can remove the id from the gson/params before, and manually assign the id later.

def id = params.remove('id')
MyDomainClass domain = new MyDomainClass(params)
domain.id = id

sumitgogia avatar Sep 25 '13 12:09 sumitgogia