如何在scala中使用一个字段为case类编写对称的Play Json格式化程序?

时间:2017-11-14 01:12:42

标签: scala playframework

假设我有一个带有一个字段的案例类

case class Id(value: String)

简单地说,我可以通过单独定义读取和写入来定义格式化程序:

private implicit val idReads: Reads[Id] =
    JsPath.read[String].map(Id)

private implicit val idWrites: Writes[Id] =
{
    id: Id => JsString(id.value)
}

private idFormats: Format[Id] = Format(idReads, idWrites)

文档表明有一种方法可以为这种情况定义一个对称格式化程序,但是我还没有找到使它适用于这种情况的特定咒语。我已尝试过以下内容,但收到编译错误:

private implicit val idFormats: Format[Id] =
    JsPath.format[String](Id, unlift(Id.unapply))

具体来说,我得到了这个编译错误:

[error] overloaded method value format with alternatives:
[error]   (w: play.api.libs.json.Writes[String])(implicit r: play.api.libs.json.Reads[String])play.api.libs.json.OFormat[String] <and>
[error]   (r: play.api.libs.json.Reads[String])(implicit w: play.api.libs.json.Writes[String])play.api.libs.json.OFormat[String] <and>
[error]   (implicit f: play.api.libs.json.Format[String])play.api.libs.json.OFormat[String]
[error]  cannot be applied to (Id.type, Id => String)
[error]         JsPath.format[String](Id, unlift(Id.unapply))
[error]                      ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 1 s, completed Nov 13, 2017 5:07:58 PM

read documentation,但it没有帮助我。我确定有一些可以应用于这种情况的单线程,因为对于包含两个字段的案例类来说这是微不足道的:

case class MyRow(id: Id, myNum: MyNum)

private implicit val myRowFormats: Format[MyRow] =
    ((JsPath \ "id").format[Id] and
        (JsPath \ "num").format[MyNum]) (MyRow, unlift(MyRow.unapply))

1 个答案:

答案 0 :(得分:2)

如果您真的希望将Id序列化为JSON字符串,请转到:

import play.api.libs.json._
import play.api.libs.functional.syntax._

case class Id(value: String)

implicit val idFormats: Format[Id] =
  implicitly[Format[String]].inmap(Id, unlift(Id.unapply))

Json.toJson(Id("asd")) == JsString("asd")
Json.toJson(Id("asd")).toString == "\"asd\""
Json.parse(Json.toJson(Id("asd")).toString).as[Id] == Id("asd")

我这样编写它是为了清楚地说明你没有使用基本的String格式化程序,它是在play-json中定义的。