我的示例JSON包含一个国家对象。
JSON示例1:
或者使用国家数组: Json示例2
"@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。谢谢。
case class NewUserJson(@version: String, country: Seq[CountryJson])
如果这对你不起作用,我可以分享完整的示例和测试,以确保两个 JSON 都能通过。告诉我它是否对你有用。 - Tomer