从多个 Json 字段创建单个子字段并使用 Play-json 应用于结果对象

约翰

我正在尝试使用 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编写一个,给定locationJSON 对象,如下所示:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章