从 playframework scala 中的 json 数组中读取元素

read elements from json array in playframework scala

给定一个 json:

val json = """
{
  "persons": [
    {"name": "Foo", "age": 21},    
    {"name": "Bar", "age": 22},
    {"name": "Baz", "age": 23}
  ]
}
"""

如何构建一个剧本 Reads[List[String]],它将从 json 中提取姓名列表?

import play.api.libs.json._

val reads: Reads[List[String]] = ???

val names: List[String] = reads.reads(Json.parse(json)) 
// expecting List("Foo", "Bar", "Baz")

可以尝试解决方法吗?


final case class Person(name: String, age: Int)
object Person {
  implicit val PersonFormat = Json.format[Person]
}


val jsonStr= """
{
  "persons": [
    {"name": "Foo", "age": 21},
    {"name": "Bar", "age": 22},
    {"name": "Baz", "age": 23}
  ]
}
"""

(Json.parse(jsonStr) \ "persons").as[List[Person]].map(p => p.name)



((Json.parse(jsonStr) \ "persons") \ "name").map(_.as[String])

只需与 Reads 组合即可。

import play.api.libs.json._

val input = Json.parse("""
{
  "persons": [
    {"name": "Foo", "age": 21},    
    {"name": "Bar", "age": 22},
    {"name": "Baz", "age": 23}
  ]
}
""")

val nameReads = (JsPath \ "name").read[String]
val listReads: Reads[Seq[String]] = Reads.seq(nameReads)

(input \ "persons").validate(listReads)
// JsSuccess(Vector(Foo, Bar, Baz),)