简体   繁体   English

Scala Play:如何将 JSON 数组结构映射到 Case Class

[英]Scala Play: How to map JSON array structure to Case Class

I'm completely new to Scala and Play and i stumbled upon the following the problem:我对 Scala 和 Play 完全陌生,我偶然发现了以下问题:

Given the following JSON structure:给定以下 JSON 结构:

[
  {
    "name": "Adam",
    "age": 19
  },
  {
    "name": "Berta",
    "age": 22
  },
...
]

I would like to map this JSON to a case classes like this:我想将此 JSON 映射到这样的案例类:

case class User(name: String, age: Int)
case class Users(users: Seq[User])

or at least something like Seq[User] .或至少像Seq[User]类的东西。

I don't know how to traverse the JsPath because there is no key.不知道怎么遍历JsPath,因为没有key。

I tried to define an implicit read but either he cannot resolve the symbol "read" or he cannot found an implicit for user.我试图定义一个隐式读取,但要么他无法解析符号“读取”,要么他找不到用户的隐式。

object User {
  implicit val reads: Reads[User] = Json.reads[User]
}
object Users {
  implicit val usersReads: Reads[Users] = (
    (JsPath).read[Seq[User]]
  )(Users.apply _)
}

How can I map my JSON to a working model?如何将我的 JSON 映射到工作模型?

Something like this will work像这样的东西会起作用

import play.api.libs.json._

case class User(name: String, age: Int)
case class Users(users: Seq[User])

object User {
  implicit val reads = Json.reads[User]
}

object Users {
  implicit val reads: Reads[Users] = Reads {
      _.validate[Seq[User]].map(Users(_))
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM