unmarshall嵌套json in spray-json

时间:2013-11-19 17:47:02

标签: akka spray spray-json

使用spray-json(因为我正在使用spray-client)为了从google maps API获取纬度,经度对象,我需要设置整个响应结构:

case class AddrComponent(long_name: String, short_name: String, types: List[String])
case class Location(lat: Double, lng: Double)
case class ViewPort(northeast: Location, southwest: Location)
case class Geometry(location: Location, location_type: String, viewport: ViewPort)
case class EachResult(address_components: List[AddrComponent],
                      formatted_address: String,
                      geometry: Geometry,
                      types: List[String])
case class GoogleApiResult[T](status: String, results: List[T])

object AddressProtocol extends DefaultJsonProtocol {
    implicit val addrFormat = jsonFormat3(AddrComponent)
    implicit val locFormat = jsonFormat2(Location)
    implicit val viewPortFormat = jsonFormat2(ViewPort)
    implicit val geomFormat = jsonFormat3(Geometry)
    implicit val eachResFormat = jsonFormat4(EachResult)
    implicit def GoogleApiFormat[T: JsonFormat] = jsonFormat2(GoogleApiResult.apply[T])
}
import AddressProtocol._

有什么方法我可以从响应中的json中获取Location并避免所有这些gumph?

喷涂客户端代码:

implicit val system = ActorSystem("test-system")
import system.dispatcher

private val pipeline = sendReceive ~> unmarshal[GoogleApiResult[EachResult]]

def getPostcode(postcode: String): Point = {
    val url = s"http://maps.googleapis.com/maps/api/geocode/json?address=$postcode,+UK&sensor=true"
    val future = pipeline(Get(url))
    val result = Await.result(future, 10 seconds)
    result.results.size match {
        case 0 => throw new PostcodeNotFoundException(postcode)
        case x if x > 1 => throw new MultipleResultsException(postcode)
        case _ => {
            val location = result.results(0).geometry.location
            new Point(location.lng, location.lat)
        }
    }
}

或者我怎样才能将jackson与喷雾客户端一起使用?

1 个答案:

答案 0 :(得分:2)

遵循jrudolph对json镜头的建议我也得到了相当多的摆弄,但终于有了工作。我发现这很困难(作为一个新手),而且我确信这个解决方案远非最优雅的 - 但我认为这可能会帮助人们或激励他人改进。

鉴于JSON:

{
    "status": 200,
    "code": 0,
    "message": "",
    "payload": {
        "statuses": {
            "emailConfirmation": "PENDING",
            "phoneConfirmation": "DONE",
        }
    }
}

仅用于解组statuses的案例类:

case class UserStatus(emailConfirmation: String, phoneConfirmation: String)

可以做到这一点来解决反应:

import scala.concurrent.Future
import spray.http.HttpResponse
import spray.httpx.unmarshalling.{FromResponseUnmarshaller, MalformedContent}
import spray.json.DefaultJsonProtocol
import spray.json.lenses.JsonLenses._
import spray.client.pipelining._

object UserStatusJsonProtocol extends DefaultJsonProtocol {
  implicit val userStatusUnmarshaller = new FromResponseUnmarshaller[UserStatus] {
    implicit val userStatusJsonFormat = jsonFormat2(UserStatus)
    def apply(response: HttpResponse) = try {
      Right(response.entity.asString.extract[UserStatus]('payload / 'statuses))
    } catch { case x: Throwable =>
      Left(MalformedContent("Could not unmarshal user status.", x))
    }
  }
}
import UserStatusJsonProtocol._

def userStatus(userId: String): Future[UserStatus] = {
  val pipeline = sendReceive ~> unmarshal[UserStatus]
  pipeline(Get(s"/api/user/${userId}/status"))
}