在我的Grails应用程序,原来的日期从数据库中读取等于:Grails的JSON的Marshaller显示不同的日期值比原来的日期
{ endDate=2015-10-19 19:00:00.0}
虽然JSON的结果是:
{"endDate": "2015-10-19T16:00:00Z"}
我认为这可能与时区转换有关。如何在JSON中显示没有任何时区转换的原始日期?
在我的Grails应用程序,原来的日期从数据库中读取等于:Grails的JSON的Marshaller显示不同的日期值比原来的日期
{ endDate=2015-10-19 19:00:00.0}
虽然JSON的结果是:
{"endDate": "2015-10-19T16:00:00Z"}
我认为这可能与时区转换有关。如何在JSON中显示没有任何时区转换的原始日期?
根据您所在的时区,2015-10-19 19:00:00.0
和2015-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 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视图。
如果我的记忆是正确的,JSON规范实际上并没有定义日期格式的格式。但每个人都使用ISO 8601,所以它有点像事实上的标准。而大多数只是总是使用祖鲁时区。
我前一段时间搜索自己,强迫Grails JSON在特定时间段内呈现日期,但失败。在我的Grails网络应用程序中,我只是将日期字段声明为文本,并将其格式化为我自己的代码中的适当时区和格式。从好的一面来看,它还有一个额外的好处,你可以保证它在未来保持这种状态。 (我是,从1.1左右开始使用Grails,并且确实在数次出现重大更改)。