Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 从多个Json字段创建单个子字段,并使用Play Json应用于结果对象_Scala_Playframework_Playframework 2.0_Play Json - Fatal编程技术网

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

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

我正在尝试使用play json读取将以下json转换为结果的case类。但是,我仍然停留在将经度和纬度json值转换为点对象的语法上,同时将其余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))

基本上,
读取[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
classes
apply
方法作为捷径,但您也可以轻松地获取
(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 _)