Question

I am using LocalTime duration for a WorkDone domain class field in grails. When using render as JSON this field is rendered as a String not as a Object. I thought that this was because of toString() method in this class.

class WorkDone{
   LocalTime duration
}

Json output = {"duration":"00:00:00"}

But if I implement this field with my custom class CustomDuration its displaying the whole object in generated JSON string. I have also implemented toString() method in this class.

class WorkDone{
    CustomDuration duration
}

json output = {"duration":{ durFieldInDurationClass:"00:00:00"}}

Why am I seeing this behaviour?

I have this map in both cases:

grails.converters.JSON.registerObjectMarshaller(WorkDone ) {
def returnMap = [:]
returnMap.put("duration", it.duration)
return returnMap
}

My custom duration class

 class CustomDuration{
     String durFieldInDurationClass
     String toString(){
       return durFieldInDurationClass
     }
    }

I am using render workdoneobject as JSON in controller to generate this output.

Was it helpful?

Solution

class CustomDuration{
 String durFieldInDurationClass
 String toString(){
   return durFieldInDurationClass
 }
 static {
  grails.converters.JSON.registerObjectMarshaller(CustomDuration) {
     return it.duration
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top