0

Given the JSON...

[ {"ID": "foo"}, {"ID": "bar"} ]

Represented with case classes...

case class Example(models: List[Model])
case class Model(id: String)

I attempt the following which fails with overloaded method value read with alternatives.

trait JsonReader {
  implicit val modelReads: Reads[Model] = (__ \ "name").read[String](Model)
  implicit val exampleReads: Reads[Example] = JsPath.read[List[Model]](Example)
  def get (response: Response) = response.json.as[Example]
}

What is the correct way to parse this?

4

1 回答 1

0

出于一个奇怪的原因,我没有找到一个优雅的解决方案来读取只有一个值的 json 模型。对于 2 个或更多值,您可以编写:

implicit val reader = (
(__ \ 'id).read[Long] and
(__ \ 'field1).read[String] and
(__ \ 'field2).read[String])(YourModel.apply _)

对于具有 1 个字段的 json 尝试使用类似的东西:

implicit val reader = new Reads[Model] {
    def reads(js: JsValue): JsResult[Model] = {
      JsSuccess(Model((js \ "name").as[String]))
    }
  }

这应该可行,但看起来不太好:(

于 2013-09-05T07:23:32.587 回答