0

I am trying to parse a Json object that consists only of an top level array without a key.

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 Answers 2

3

One possiblity is by creating an implicit Reads function:

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

  implicit val NamesFormat = readNames
Sign up to request clarification or add additional context in comments.

2 Comments

It seems rather ham-fisted to wrap Seq within another container, though.
Its necessary because I have a method query[T](qs: String)(implicit r: Read[T]): NonEmptyList[String] \/ T . and in the method it calls a web service and the response is parsed: Json.parse(s).validate[T]
2

You don't need to specify Reads for Seq[Name] if you already have one defined for 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)),)

3 Comments

But I would like to write Json.parse(s).validate[Names]. Is this possible?
Not without a key like you have it. But why duplicate the code when the above method works perfectly fine?
Its possible and I actually need it to abstract over Reads[T]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.