0

我正在尝试使用 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))
4

1 回答 1

1

从根本上说,aReads[T]只需要一个将元组转换为 的实例的函数T。因此,给定JSON 对象,您可以为您的Point类编写一个,如下所示:location

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 _)

在第二种情况下,我们使用BusinessInputclassesapply方法作为捷径,但您可以轻松地获取一个元组(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 _)
于 2017-08-26T16:59:26.173 回答