[英]Scala: Map part of Json to Object with playframework
I'm relatively new to Scala.我对 Scala 比较陌生。 I would like to map part of my Json to my Object.
我想将我的 Json 的一部分映射到我的对象。 Code looks like this:
代码如下所示:
def seasons = (json \\ "season")
case class:案例类:
case class Season(startDate: LocalDate, endDate: LocalDate)
json-structure: json结构:
[
{
"id": "",
"name": "",
"season": {
"start": "0",
"end": "0"
}
}
]
I would somehow like to end up with a List[Season], so I can loop through it.我想以某种方式结束一个 List[Season],这样我就可以遍历它。
json-structure:
[
{
"id": "",
"name": "",
"season": {
"start": "0",
"end": "0"
}
},
{
"id": "",
"name": "",
"season": {
"start": "0",
"end": "0"
}
}...
]
Json (which is a JsValue btw) brings multiple regions as can be seen above. Json(顺便说一句,这是一个 JsValue)带来了多个区域,如上所示。 Case classed are provided (Region holds a Season), naming is the same as in json.
提供案例分类(Region 持有一个 Season),命名与 json 中相同。 Formats look like this:
格式如下所示:
implicit val seasonFormat: Format[Season] = Json.format[Season]
implicit val regionFormat: Format[Region] = Json.format[Region]
So what would I need to call in order to get a List[Region]?那么我需要调用什么才能获得 List[Region]? I thought of something like
regionsJson.as[List[Region]]
as I defined the Format, which provides me the Read/Write possibilities.我在定义格式时想到了
regionsJson.as[List[Region]]
类的东西,它为我提供了读/写的可能性。 But unfortunately, it's not working.但不幸的是,它不起作用。
What is the best way doing this?这样做的最佳方法是什么? I've tried it with an JsArray, but I have difficulties with mapping it...
我已经用 JsArray 试过了,但我很难映射它......
Any input would be much appreciated!任何输入将不胜感激!
I've added some changes to your original case class
and renamed its fields to match json fields.我对您的原始
case class
添加了一些更改,并将其字段重命名为匹配 json 字段。
The following code does parsing of the json into Seq[Session]
以下代码将 json 解析为
Seq[Session]
import java.time.LocalDate
import play.api.libs.json._
case class Season(start: LocalDate, end: LocalDate)
implicit val sessionFormat: Format[Season] = Json.format[Season]
val json =
"""
|[
| {
| "id": "",
| "name": "",
| "season": {
| "start": "2020-10-20",
| "end": "2020-10-22"
| }
| }
|]
|""".stripMargin
val seasonsJson: collection.Seq[JsValue] = Json.parse(json) \\ "season"
val seasons: collection.Seq[Season] = seasonsJson.map(_.as[Season])
seasons.foreach(println)
Please note that I changed the data of your json and instead of 0
, which is not a valid date, I provided dates in iso format yyyy-mm-dd
.请注意,我更改了您的 json 数据,而不是
0
,这不是有效日期,而是以 iso 格式yyyy-mm-dd
提供日期。
The above code works with play-json version 2.9.0.上面的代码适用于 play-json 2.9.0 版。
---UPDATE--- - -更新 - -
Following up comment by @cchantep.跟进@cchantep 的评论。
Method as
will produce an exception if json cannot be mapped in case class, a non-exception option is to use asOpt
that does not throw an exception but returns a None
if mapping is not possible.如果无法在 case 类中映射 json,则
as
方法将产生异常,非异常选项是使用asOpt
,它不会引发异常,但如果无法映射,则返回None
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.