使用 play json 写入时转换类型
Converting types when using play json writes
从这个问题开始
我有一个 Date 对象,我想以特定格式将其写入 json 中的字符串。
implicit val tokenWrites: Writes[Token] = (
(JsPath \ "creation_date").write[Date] and
(JsPath \ "expires").writeNullable[Date]
)(unlift(Token.unapply))
我想json被编辑为:
"creation_date": "2014-05-22T08:05:57.556385+00:00"
要将字符串转换为我使用的日期:
def strToDate(string2: String): Date = {
val df2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
df2.parse(string2);
}
然后映射到读取中,但这似乎无法通过写入实现
遵循write
的定义
def write[T](implicit w: Writes[T])
您可以创建自己的 Writes[T]
并使用它。
例如
object dateWrite extends Writes[Date] {
override def writes(o: Date): JsValue = JsString("some formatted date")
}
会把o:Date
写成JsString("some formatted date")
(可以用自己的格式:Date => JsValue),然后在write
中用自己的Writes[T]
:
implicit val tokenWrites: Writes[Token] = (
(JsPath \ "creation_date").write[Date](dateWrite) and
(JsPath \ "expires").writeNullable[Date](dateWrite)
) (unlift(Token.unapply))
结果
tokenWrites.writes(Token(new Date(), Some(new Date())))
将会
res1: play.api.libs.json.JsValue = {"creation_date":"some formatted date","expires":"some formatted date"}
从这个问题开始
我有一个 Date 对象,我想以特定格式将其写入 json 中的字符串。
implicit val tokenWrites: Writes[Token] = (
(JsPath \ "creation_date").write[Date] and
(JsPath \ "expires").writeNullable[Date]
)(unlift(Token.unapply))
我想json被编辑为:
"creation_date": "2014-05-22T08:05:57.556385+00:00"
要将字符串转换为我使用的日期:
def strToDate(string2: String): Date = {
val df2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
df2.parse(string2);
}
然后映射到读取中,但这似乎无法通过写入实现
遵循write
def write[T](implicit w: Writes[T])
您可以创建自己的 Writes[T]
并使用它。
例如
object dateWrite extends Writes[Date] {
override def writes(o: Date): JsValue = JsString("some formatted date")
}
会把o:Date
写成JsString("some formatted date")
(可以用自己的格式:Date => JsValue),然后在write
中用自己的Writes[T]
:
implicit val tokenWrites: Writes[Token] = (
(JsPath \ "creation_date").write[Date](dateWrite) and
(JsPath \ "expires").writeNullable[Date](dateWrite)
) (unlift(Token.unapply))
结果
tokenWrites.writes(Token(new Date(), Some(new Date())))
将会
res1: play.api.libs.json.JsValue = {"creation_date":"some formatted date","expires":"some formatted date"}