【问题标题】:Why is Joda LocalTime being render as String in Json Grails?为什么 Joda LocalTime 在 Json Grails 中呈现为字符串?
【发布时间】:2013-12-04 19:08:53
【问题描述】:

我正在为 grails 中的 WorkDone 域类字段使用 LocalTime 持续时间。当使用呈现为 JSON 时,此字段被呈现为字符串而不是对象。我认为这是因为这个类中的 toString() 方法。

class WorkDone{
   LocalTime duration
}

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

但是,如果我使用自定义类 CustomDuration 实现此字段,它会在生成的 JSON 字符串中显示整个对象。 我也在这个类中实现了 toString() 方法。

class WorkDone{
    CustomDuration duration
}

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

为什么我会看到这种行为?

这两种情况我都有这张地图:

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

我的自定义持续时间类

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

我在控制器中使用render workdoneobject as JSON 来生成这个输出。

【问题讨论】:

    标签: json grails groovy render localtime


    【解决方案1】:
    class CustomDuration{
     String durFieldInDurationClass
     String toString(){
       return durFieldInDurationClass
     }
     static {
      grails.converters.JSON.registerObjectMarshaller(CustomDuration) {
         return it.duration
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-12-24
      • 1970-01-01
      • 2014-08-11
      • 1970-01-01
      • 1970-01-01
      • 2013-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多