如何将从 HTTP 请求收到的天数 Json 解析为 Scala 和 Play Framework 中的列表
How to parse a Json with days received from HTTP request into a list in Scala and Play Framework
我是 Scala 和 Play Framework 的新手。
我有一个 Json 这样的:
{
"monday" : [],
"tuesday" : [
{
"type" : "xyz",
"value" : 1111
},
{
"type" : "abc",
"value" : 2222
}
],
.....
}
我正在尝试在列表或地图中读取此 Json,其中每个条目都包含 type/value 的列表。
我定义了一个读取 HTTP 请求正文的方法
def readJson() = Action { implicit request =>
val body = request.body
val jsonObject = body.asJson
}
我不明白如何继续,我已经阅读了 Play Framework 文档,但我有点迷茫。
任何人都可以帮忙吗?谢谢!
你可以关注这个
import play.api.libs.json._
final case class Task(
`type`: String,
value: Int
)
final case class Days(
monday: List[Task],
tuesday: List[Task]
)
implicit val ts = Json.format[Task]
implicit val da = Json.format[Days]
def readJson() = Action { implicit request =>
val days:Option[Days] = request.body.asJson.getOrElse(Json.obj()).asOpt[Days]
// .....
}
或者不将 json 映射到案例 class,您可以使用 jsPath 参见 https://www.playframework.com/documentation/2.8.x/ScalaJsonCombinators
我是 Scala 和 Play Framework 的新手。 我有一个 Json 这样的:
{
"monday" : [],
"tuesday" : [
{
"type" : "xyz",
"value" : 1111
},
{
"type" : "abc",
"value" : 2222
}
],
.....
}
我正在尝试在列表或地图中读取此 Json,其中每个条目都包含 type/value 的列表。 我定义了一个读取 HTTP 请求正文的方法
def readJson() = Action { implicit request =>
val body = request.body
val jsonObject = body.asJson
}
我不明白如何继续,我已经阅读了 Play Framework 文档,但我有点迷茫。 任何人都可以帮忙吗?谢谢!
你可以关注这个
import play.api.libs.json._
final case class Task(
`type`: String,
value: Int
)
final case class Days(
monday: List[Task],
tuesday: List[Task]
)
implicit val ts = Json.format[Task]
implicit val da = Json.format[Days]
def readJson() = Action { implicit request =>
val days:Option[Days] = request.body.asJson.getOrElse(Json.obj()).asOpt[Days]
// .....
}
或者不将 json 映射到案例 class,您可以使用 jsPath 参见 https://www.playframework.com/documentation/2.8.x/ScalaJsonCombinators