在 Scala 中将自定义对象 JSON 编写为简单值 (JSON Reads/Writes)

Writing custom object JSON as a simple value in Scala (JSON Reads/Writes)

我在 Scala 中有一个自定义数据类型:

case class GPID(value: Int) {
    // ... other stuff ...

    implicit val writesGPID = new Writes[GPID] {
        def writes(g: GPID): JsValue = {
            Json.obj(
                "GPID" -> g.value
            )
        }
    }

    implicit val reads: Reads[GPID] = (
        (__ \ "GPID").read[Int]
        ).map(GPID(_))
}

如您所见,它有一个 reads/writes 方法,但这导致输出如下:

"id":{"GPID":1000}

但是,我们只是希望它 serialize/deserialize 像一个普通的 Int:

"id":1000

我一直在想办法重写 reads/writes,但运气不太好...任何建议都将不胜感激!

谢谢。

我添加了一些验证,根据您的需要修改。

object GPID {
  def unapply(in: Int): Option[GPID] = Option(in).filter(_ > 0).map(apply)

  implicit val reads = new Reads[GPID] {
    def reads(in: JsValue) =
      Option(in)
        .flatMap {
          case JsNumber(value) => Some(value)
          case _ => None
        }
        .flatMap(num => unapply(num.toInt))
        .map(JsSuccess(_, __))
        .getOrElse(JsError(__, "validate.error.expected.GPID"))
  }

  implicit val writes = new Writes[GPID] {
    def writes(g: GPID) = JsNumber(g.value)
  }

}