我正在尝试使用 play-json 读取将以下 Json 转换为生成的案例类。但是,我坚持将经度和纬度 json 值转换为 Point 对象的语法,同时将其余的 json 值转换为相同的结果 BusinessInput 对象。这在语法上可能吗?
case class BusinessInput(userId: String, name: String, location: Point, address: Option[String], phonenumber: Option[String], email: Option[String])
object BusinessInput {
implicit val BusinessInputReads: Reads[BusinessInput] = (
(__ \ "userId").read[String] and
(__ \ "location" \ "latitude").read[Double] and
(__ \ "location" \ "longitude").read[Double]
)(latitude: Double, longitude: Double) => new GeometryFactory().createPoint(new Coordinate(latitude, longitude))
从根本上说, aReads[T]
只需要一个将元组转换为 的实例的函数T
。因此,您可以为您的Point
类编写一个,给定location
JSON 对象,如下所示:
implicit val pointReads: Reads[Point] = (
(__ \ "latitude").read[Double] and
(__ \ "longitude").read[Double]
)((lat, lng) => new GeometryFactory().createPoint(new Coordinate(lat, lng))
然后将其与BusinessInput
班级的其余数据结合起来:
implicit val BusinessInputReads: Reads[BusinessInput] = (
(__ \ "userId").read[String] and
(__ \ "name").read[String] and
(__ \ "location").read[Point] and
(__ \ "address").readNullable[String] and
(__ \ "phonenumber").readNullable[String] and
(__ \ "email").readNullable[String]
)(BusinessInput.apply _)
在第二种情况下,我们使用BusinessInput
classesapply
方法作为捷径,但您可以轻松地使用一个元组(userId, name, point)
并创建一个省略可选字段的元组。
如果您不想Point
单独读取,只需使用相同的原则将它们组合起来:
implicit val BusinessInputReads: Reads[BusinessInput] = (
(__ \ "userId").read[String] and
(__ \ "name").read[String] and
(__ \ "location").read[Point]((
(__ \ "latitude").read[Double] and
(__ \ "longitude").read[Double]
)((lat, lng) => new GeometryFactory().createPoint(new Coordinate(lat, lng)))) and
(__ \ "address").readNullable[String] and
(__ \ "phonenumber").readNullable[String] and
(__ \ "email").readNullable[String]
)(BusinessInput.apply _)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句