2

With Play/Scala, I try to transform this json:

val json = Json.parse(""" 
{
  "name": "John Doe",
  "location": { 
    "lon": 48.858596, 
    "lat": 2.294481 
  }
} 
""")

into this result:

val result = Json.parse(""" 
{ 
  "name": "John Doe", 
  "location": { 
    "type": "Point", 
    "coordinates": [48.858596, 2.294481] 
  }
} 
""")

Any idea how to apply the magic? Here's what i tried:

import play.api.libs.json._
import play.api.libs.json.Reads._
import play.api.libs.functional.syntax._

val transformer = {
    val locationField = __ \ "location"
    val lon = (locationField \ "lon").json.pick
    val lat = (locationField \ "lat").json.pick

    __.json.update((
        (locationField \ "type").json.put( JsString("Point") ) and
        (locationField \ "coordinates").json.put( JsArray() )).reduce
      andThen
        (locationField \ "coordinates").json.update(of[JsArray].map { // How to add lon/lat into JsArray?????
          case JsArray(arr) => JsArray(arr :+ JsNumber(3L))
          }
        )
      andThen (
        (locationField \ "lon").json.prune and
        (locationField \ "lat").json.prune).reduce
    )
  }

json.transform(transformer)

Get the code here: https://gist.github.com/chrissom/20c5aa254210d7c32f53479df6a66f68

4

1 回答 1

1

假设导入:

import play.api.libs.json._

您可以定义一个Location表示该值的location值。

case class Location(lon: Double, lat: Double) {
  def toPoint: JsObject = {
    Json.obj(
      "type" -> "Point",
      "coordinates" -> Json.arr(lon, lat)
    )
  }
}

object Location {
  implicit val reads: Reads[Location] = Json.reads[LonLat]
}

现在你可以这样做:

val locationJson = Json.parse("""{"lon": 48.858596, "lat": 2.294481}""")

locationJson.transform(of[LonLat].map(_.toPoint))
// Output: 
// JsSuccess({"type":"Point","coordinates":[48.858596,2.294481]},)

现在您可以将其插入到转换中,例如:

(__ \ 'location).json.update(of[LonLat].map(_.toPoint))

但是在此转换中,您将剩下latlon字段。所以删除它们:

(__ \ 'location).json.update(of[LonLat].map(_.toPoint)) andThen
  (__ \ 'location \ 'lat).json.prune andThen
  (__ \ 'location \ 'lon).json.prune

在我看来,不可能将其简化为update同类中唯一的操作 - 这恰好是深度合并。

于 2017-02-18T09:55:29.170 回答