作者:bv方法_484 | 来源:互联网 | 2023-09-07 18:18
IamcurrentlyusingthePlayframeworkjsonparserinordertoparseajsonstringinmyscalacode
I am currently using the Play framework json parser in order to parse a json string in my scala code.
我目前正在使用Play框架json解析器来解析我的scala代码中的json字符串。
I have the following class:
我有以下课程:
case class Address(address: String,
gps: GPS,
country: String) {}
object Address {
implicit val reads: Reads[Address] = (
(JsPath \ "address").read[String] and
(JsPath \ "gps").read[GPS] and
(JsPath \ "country").read[String]
) (Address.apply _)
implicit val writes: Writes[Address] = (
(JsPath \ "address").write[String] and
(JsPath \ "gps").write[GPS] and
(JsPath \ "country").write[String]
) (unlift(Address.unapply))
}
Which works fine with the following json:
哪个适用于以下json:
{
"address": "123 Fake Street",
"country": "USA",
"gps": { ... }
}
The problem is that in some situations the json may instead have the gps field be a string which doesnt parse, i.e.
问题是在某些情况下,json可能会将gps字段改为不解析的字符串,即
{
"address": "123 Fake Street",
"country": "USA",
"gps": "123abc"
}
Now I know that I cant have the gps member be both a string or a GPS object, but is there any way to have it be say an Option[GPS] and only have a value if the json contained a gps object?
现在我知道我不能让gps成员同时成为一个字符串或一个GPS对象,但有没有办法让它说一个选项[GPS]并且只有一个值,如果json包含一个gps对象?
1 个解决方案