简体   繁体   English

Scala / Jerkson:在Json中指定Date对象的格式

[英]Scala/Jerkson: Specifying the format of Date objects in Json

I am serializing an object containing a Date using the Jerkson Json library (wrapper for Jackson ): 我正在使用Jerkson Json库Jackson的包装器)对包含Date的对象进行序列化:

import com.codahale.jerkson.Json
import java.util.Date

case class JTest(
    val dTest: Date
)

val jt = new JTest(new Date())
println(Json.generate(jt))

Which results in: 结果是:

{"dTest":1353576079168}

Is there any way I can specify the format or override the generating function? 有什么办法可以指定格式或覆盖生成函数?

I realize that Json doesn't have a proper Date type, so the output (unix time in millis) is "correct". 我意识到Json没有正确的Date类型,因此输出(以毫秒为单位的unix时间)是“正确的”。 I'd like to have my Dates serialized as strings in the ISO 8601 (with time/timezone) format: 2007-04-05T01:12:22+0100 , as it's easily parsed and human readable. 我想将日期序列化为ISO 8601 (带有时间/时区)格式的字符串: 2007-04-05T01:12:22+0100 ,因为它易于解析且易于阅读。 Date 's toString spits out Thu Nov 22 10:27:54 CET 2012 . Date的toString Thu Nov 22 10:27:54 CET 2012

There are two issues here. 这里有两个问题。 Firstly, the minor issue of ISO8601 dates - these are achievable using SimpleDateFormat, eg 首先,ISO8601日期的次要问题-这些日期可以使用SimpleDateFormat实现,例如

import java.text._
import java.util._
val d1 = new Date()
val sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
println(sdf.format(d1))

The formatter will parse as well as format. 格式化程序将解析和格式化。 Remember not to share it between threads (instead always create an instance in local scope before use) because it isn't thread-safe. 记住不要在线程之间共享它(而是总是在使用前在本地范围内创建一个实例),因为它不是线程安全的。

Secondly, the more tricky issue of using dates automatically in Jerkson. 其次,在Jerkson中自动使用日期更为棘手。 This appears to be one feature of Jerkson that is inferior to Lift-json. 这似乎是Jerkson的一项功能,不如Lift-json。 The latter allows custom parser/formatter code to be inserted into the parsing layer. 后者允许将自定义解析器/格式器代码插入解析层。 Jerkson does not, I think. 我认为杰克森没有。

We got round this limitation simply by ignoring it. 我们通过忽略它来绕过此限制。 We like the superior performance of Jerkson, so we just use Long and String for our date transmission and we deal with the parsing separately. 我们喜欢Jerkson的出色性能,因此我们只使用Long和String进行日期传输,所以我们分别处理解析。 For example 例如

case class JTest(val dTest: String) {
  lazy val dTestDate: Date = {
    val sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
    sdf.parse(dTest)
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM