WeiChing 林煒清
WeiChing 林煒清

Reputation: 4469

Scala Play Json can't read on hetero-type json array

Using "com.typesafe.play" %% "play-json" % "2.4.0-M3"

val json=Json.parse("""[1,"second",3]""")

case class C123(arg1: Int, arg2: String, arg3: Int)
implicit val c123Reads: Reads[C123] = (
          JsPath(1).read[Int] and 
          JsPath(2).read[String] and 
          JsPath(3).read[Int]
          )(C123)

println(json.as[C123]) //fail

I can not figure out why this failed, what is the right way doing it?


This is error log, for whoever is capable to understand .

Exception in thread "main" play.api.libs.json.JsResultException: JsResultException(errors:List(((2),List(ValidationError(error.expected.jsstring,WrappedArray()))), ((1),List(ValidationError(error.expected.jsnumber,WrappedArray()))), ((3),List(ValidationError(error.expected.jsnumber,WrappedArray())))))

Sadly, there's no default Tuple reader in Play-Json.

Upvotes: 0

Views: 302

Answers (1)

Nikita
Nikita

Reputation: 4515

List indices must start from 0, not from 1.

implicit val c123Reads: Reads[C123] = (
          JsPath(0).read[Int] and 
          JsPath(1).read[String] and 
          JsPath(2).read[Int]
          )(C123)

scala> println(json.as[C123])
C123(1,second,3)

Upvotes: 1

Related Questions