Why is Joda LocalTime being render as String in Json Grails?

123 views Asked by At

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.

1

There are 1 answers

0
Yash Agarwal On BEST ANSWER
class CustomDuration{
 String durFieldInDurationClass
 String toString(){
   return durFieldInDurationClass
 }
 static {
  grails.converters.JSON.registerObjectMarshaller(CustomDuration) {
     return it.duration
    }
}