[英]Play Framework and Scala Json, parsing for json containing JSArray and JSObject
我的樣本json要么是國家對象Json樣本1
"@version": "1.0",
"country": {
"@country": "US",
"day": {
"@date": "2016-02-15",
"@value": "1"
}
}
或者使用國家/地區數組: Json示例2
"@version": "1.0",
"country": [{
"@country": "US",
"day": {
"@date": "2016-02-15",
"@value": "1"
}
}, {
"@country": "UK",
"day": {
"@date": "2016-02-15",
"@value": "5"
}]
}
閱讀json
implicit val dayJsonReads: Reads[DayJson] = (
(JsPath \ "@date").read[DateTime](dateReads) and
((JsPath \ "@value").read[Int] orElse (JsPath \ "@value").read[String].map(_.toInt))
)(DayJson.apply _)
implicit val countryJsonReads: Reads[CountryJson] = (
(JsPath \ "@country").read[String] and
(JsPath \ "day").read[DayJson]
)(CountryJson.apply _)
implicit val newUserJsonReads: Reads[NewUserJson] = (
(JsPath \ "@version").read[String] and
(JsPath \ "country").readNullable[Seq[CountryJson]]
)(NewUserJsonParent.apply _)
上面的代碼讀取示例json 2但是對於示例json 1失敗。是否可以使用readNullable來讀取JS Value或JS Object,或者我們可以將它從JS Value轉換為JS Object。 謝謝。
你可以這樣做:
object NewUserJson{
implicit val newUserJsonReads: Reads[NewUserJson] = (
(JsPath \ "@version").read[String] and
(JsPath \ "country").read[JsValue].map{
case arr: JsArray => arr.as[Seq[CountryJson]]
case obj: JsObject => Seq(obj.as[CountryJson])
}
)(NewUserJson.apply _)
}
這適用於此案例類:
case class NewUserJson(`@version`: String, country: Seq[CountryJson])
但我不喜歡它,你不能只使用相同的結構,當你只有一個國家只發送一個只包含一個國家的列表而不是對象?
使用Tomer的解決方案,下面是一個工作樣本。 如果我能讓它更緊湊,那就太好了。
案例類
case class NewUserJson(version: String, country: Option[Seq[CountryJson]])
Json解析對象
object NewUserJson{
implicit val newUserJsonReads: Reads[NewUserJson] = (
(JsPath \ "@version").read[String] and
(JsPath \ "country").readNullable[JsValue].map {
arr => {
if (!arr.isEmpty){
arr.get match {
case arr: JsArray => Option(arr.as[Seq[CountryJson]])
case arr: JsObject => Option(Seq(arr.as[CountryJson]))
}
}else {
None
}
}
}
)(NewUserJson.apply _)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.