json - Grails JSON Marshaller 显示的日期值与原始日期不同

在我的 Grails 应用程序中,从数据库读取的原始日期等于:

{ endDate=2015-10-19 19:00:00.0}

虽然 JSON 结果是:
{"endDate": "2015-10-19T16:00:00Z"}

我认为这可能与时区转换有关。如何在 JSON 中显示没有任何时区转换的原始日期?

最佳答案

根据您所在的时区,2015-10-19 19:00:00.02015-10-19T16:00:00Z可能不是不同的时间,它们可能只是同一时间(瞬间)的不同表示。

就我而言,我使用自定义编码器来确保我的 API 的 JSON 响应中的时间始终使用 UTC 时区。我的自定义编码器如下所示:

import org.springframework.stereotype.Component

@Component
class DateMarshaller implements CustomMarshaller {

    @Override
    def getSupportedTypes() {
        Date
    }

    @Override
    Closure getMarshaller() {
        { Date date ->

            TimeZone tz = TimeZone.getTimeZone('UTC')
            date?.format("yyyy-MM-dd'T'HH:mm:ss'Z'", tz)
        }
    }
}

请记住在 Config.groovy 中注册此编码器用于 Spring bean 扫描的包.它实现的接口(interface)是:
interface CustomMarshaller {

    /**
     * Indicates the type(s) of object that this marshaller supports
     * @return a {@link Class} or collection of {@link Class} 
     * if the marshaller supports multiple types
     */
    def getSupportedTypes()

    Closure getMarshaller()
}

然后我有一个服务来注册我所有的 CustomMarshaller 实例。对于相关类型:
import grails.converters.JSON
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware

import javax.annotation.PostConstruct

class MarshallerRegistrarService implements ApplicationContextAware {

    static transactional = false

    ApplicationContext applicationContext

    // a combination of eager bean initialization and @PostConstruct ensures that the marshallers are registered when
    // the app (or a test thereof) starts
    boolean lazyInit = false

    @PostConstruct
    void registerMarshallers() {

        Map<String, CustomMarshaller> marshallerBeans = applicationContext.getBeansOfType(CustomMarshaller)

        marshallerBeans.values().each { CustomMarshaller customMarshaller ->

            customMarshaller.supportedTypes.each { Class supportedType ->
                JSON.registerObjectMarshaller supportedType, customMarshaller.marshaller
            }
        }
    }
}

这是一个相当复杂的解决方案,但就我而言,我使用的是 Grails 2.5.X。如果我使用的是 Grails 3.X,我会尝试使用 JSON View 。

https://stackoverflow.com/questions/37533228/

相关文章:

ssh - ssh是否可以回显您发送的命令?

ssh - Amazon EC2 ssh 登录失败

session - 如何存储操作的参数以供以后再次使用

grails - grails 域类中何时以及为什么应该为空或/和空白约束?

spring-mvc - 用于 'dashboard'风格UI(涉及多个域)的 Controller

ssh - 如何测量 SSH 隧道的带宽?

mongodb - Grails 3 MongoDB无法从application.yml中读取con

php - 在 PHP 中通过 SSH 与多个服务器交互

svn - 尝试结帐SVN时为什么会收到 “/RCS/trunk,v: No such file o

grails - 创建后获取域对象的ID