在playframework中没有键的解析Json序列

时间:2014-09-15 11:49:29

标签: json scala playframework-2.0

我正在尝试解析一个只包含没有键的顶级数组的Json对象。

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

case class Name(first: String, last: String)
case class Names(names: Seq[Name])

implicit val NameF = Json.format[Name]

val s = """[{"first": "A", "last": "B"},{"first": "C", "last": "D"},{"first": "E", "last": "F"}]"""

implicit val NF: Reads[Names] = (
    JsPath.read[Seq[Name]]
)(Names.apply _)

<console>:34: error: overloaded method value read with alternatives:
  (t: Seq[Name])play.api.libs.json.Reads[Seq[Name]] <and>
  (implicit r: play.api.libs.json.Reads[Seq[Name]])play.api.libs.json.Reads[Seq[Name]]
 cannot be applied to (Seq[Name] => Names)
            JsPath.read[Seq[Name]]

2 个答案:

答案 0 :(得分:2)

如果已经为Reads定义了Seq[Name],则无需为Name指定case class Name(first: String, last: String) implicit val NameF = Json.format[Name] val s = """[{"first": "A", "last": "B"},{"first": "C", "last": "D"},{"first": "E", "last": "F"}]""" scala> Json.parse(s).validate[Seq[Name]] res2: play.api.libs.json.JsResult[Seq[Name]] = JsSuccess(List(Name(A,B), Name(C,D), Name(E,F)),)

{{1}}

答案 1 :(得分:1)

一种可能性是通过创建隐式读取函数:

  def readNames: Reads[Names] = new Reads[Names] {
    def reads(json: JsValue) = {
      json.validate[Seq[Name]].map(succ => Names(succ))
    }
  }

  implicit val NamesFormat = readNames