Scala 从多个Json字段创建单个子字段,并使用Play Json应用于结果对象
我正在尝试使用play json读取将以下json转换为结果的case类。但是,我仍然停留在将经度和纬度json值转换为点对象的语法上,同时将其余json值转换为相同的结果BusinessInput对象。 这在句法上是可能的吗Scala 从多个Json字段创建单个子字段,并使用Play Json应用于结果对象,scala,playframework,playframework-2.0,play-json,Scala,Playframework,Playframework 2.0,Play Json,我正在尝试使用play json读取将以下json转换为结果的case类。但是,我仍然停留在将经度和纬度json值转换为点对象的语法上,同时将其余json值转换为相同的结果BusinessInput对象。 这在句法上是可能的吗 case class BusinessInput(userId: String, name: String, location: Point, address: Option[String], phonenumber: Option[String], email: Opt
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))
基本上,
读取[T]
只需要一个函数,该函数将元组转换为T
的实例。因此,您可以为点
类编写一个,给定位置
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)
的元组,并创建一个不包含可选字段的元组
如果不想让点
单独读取,只需使用相同的原则组合它们:
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 _)