我是Scala的新手,并且没有办法做到这一点。
我有这堂课:
case class User(userId: Int, userName: String, email: String, password:
String) {
def this() = this(0, "", "", "")
}
case class Team(teamId: Int, teamName: String, teamOwner: Int,
teamMembers: List[User]) {
def this() = this(0, "", 0, Nil)
}
我发送邮件请求为: -
'{
"teamId" : 9,
"teamName" : "team name",
"teamOwner" : 2,
"teamMembers" : [ {
"userId" : 1000,
"userName" : "I am new member",
"email" : "eamil",
"password" : "password"
}]
}'
我得到了请求: -
我试过了: -
val data = (request.body \ "teamMembers")
val data2 = (request.body \ "teamId")
val data3 = (request.body \ "teamName")
data: [{"userId":1000,"userName":"I am new
member","email":"eamil","password":"password"}]
data2: 9
data3: "team name"
如何将数据转换为用户对象?
[{"userId":1000,"userName":"I am new
member","email":"email","password":"password"}]
答案 0 :(得分:2)
作为一种选择,您可以阅读像这样的用户
import play.api.libs.json.{JsArray, Json}
case class User(
userId: Int,
userName: String,
email: String,
password: String) {
}
case class Team(
teamId: Int,
teamName: String,
teamOwner: Int,
teamMembers: List[User]) {
}
implicit val userFormat = Json.format[User]
implicit val teamFormat = Json.format[Team]
val jsonStr = """{
"teamId" : 9,
"teamName" : "team name",
"teamOwner" : 2,
"teamMembers" : [ {
"userId" : 1000,
"userName" : "I am new member",
"email" : "eamil",
"password" : "password"
}]
}"""
val json = Json.parse(jsonStr)
// Team(9,team name,2,List(User(1000,I am new member,eamil,password)))
json.as[Team]
// Seq[User] = ListBuffer(User(1000,I am new member,eamil,password))
val users = (json \ "teamMembers").as[JsArray].value.map(_.as[User])