类型不匹配将序列转换为播放2.2.2中的JSON

时间:2014-03-07 12:36:07

标签: json playframework-2.2

您好我在这里发现了一些像stackoverflow这样的问题,但是所提供的解决方案似乎都不适用于我。

我正在测试playframework(2.2.2)并试图弄清楚如何为一个对象序列生成一个json格式。

case class Captain(
    val name: String,
    val secondname: String,
    val surname: String
)

所以在我的Controller中我有以下动作:

def captains= Action {
    Ok(getCaptains).as("application/json")
  }

和以下方法:

def getCaptains= {

    val seq = Seq[Captain](new Captain("james", "tiberius", "kirk"), new Captain("jean", "luc", "picard"))
    val jsonOutput =  Json.toJson(seq).as(Seq[Captain] _)
  }

当然这会触发:“找不到类型为Seq [models.Captain]的Json序列化程序。尝试为此类型实现隐式写入或格式。”

因此,根据播放文档和网络上的几个主题,我使用了

object Cpatain {

}

在对象中我尝试了以下解决方案:

作家方法:

1:

implicit def writes(cap: Captain): JsValue = {
    val capSeq = Seq(
      "name" -> JsString(cap.name),
      "secondname" -> JsString(cap.secondname),
      "surname" -> JsString(cap.surname)
    )
    JsObject(capSeq)
  }

2:

implicit val CaptainWrites = new Writes[Captain] {
    def writes(cap: Captain): JsValue = {
      Json.obj(
        "name" -> cap.name,
        "secondname" -> cap.secondname,
        "surname" -> cap.surname
      )
    }
  }

读者方法:

1:

implicit val regReads: Reads[Captain] = (__ \ "captains").read(
    (__ \ "name").read[String] and
      (__ \ "secondname").read[String] and
      (__ \ "surname").read[String]
      tupled
  ) map Captain.apply _

2:

 implicit val CaptainReads =
  (JsPath \ "captains").read(
    (JsPath \ "name").read[String] and
      (JsPath \ "secondname").read[String] and
      (JsPath \ "surname").read[String]
      tupled
  )

还有:

  implicit object captainFormat extends Format[Captain] {

    def writes(cap: Captain): JsValue = {
      Json.obj(
        "name" -> JsString(cap.name),
        "secondname" -> JsString(cap.secondname),
        "surname" -> JsString(cap.surname)
      )
    }
    def reads(json: JsValue): Captain= Captain(
      (json \ "name").as[String],
      (json \ "secondname").as[String],
      (json \ "surname").as[String]
    )
  }

但无论如何,我会导致: “类型不匹配;找到:Seq [models.Captain] => Seq [models.Captain] required:play.api.libs.json.Reads [?]”

这也在以下提到: type mismatch error when creating Reads for Play 2.1

Json Writes in Play 2.1.1

但是你可以看到我已经尝试了所提供的解决方案而没有成功。

所以我似乎错过了一些事情。我将不胜感激任何帮助!!

1 个答案:

答案 0 :(得分:-1)

所以我设法通过使用:

让它运行
  implicit val capReads: Reads[Captain] = (
    (__ \ "name").read[String] ~
    (__ \ "secondname").read[String] ~
    (__ \ "surname").read[String]

    )(Captain.apply _)

  implicit def writes(cap: Captain): JsValue = {
    Json.obj(
      "name" -> JsString(cap.name),
      "secondname" -> JsString(cap.surname),
      "surname" -> JsString(cap.surname2)
    )
  }