2017-08-25 4 views
0

play-jsonの読み取りを使用して、次のJsonを結果のcaseクラスに変換します。しかし、私は経緯度と緯度のjson値をPointオブジェクトに変換し、残りのjson値を同じ結果のBusinessInputオブジェクトに変換する構文に固執しています。 これは構文的に可能ですか?複数のJsonフィールドから単一のサブフィールドを作成し、Play-jsonを使用して結果のObjectに適用します。

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

答えて

1

基本的に、Reads[T]だけTのインスタンスにタプルを回す機能を必要とします。そのため、そうのように、location JSONオブジェクトを指定して、あなたのPointクラスのための1つを書くことができます。その後、

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クラスapplyメソッドをショートカットとして使用しますが、同様に簡単に(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 _) 
関連する問題