scala Spray Rest API使用RequestContext返回Json内容类型

时间:2016-06-29 13:48:09

标签: scala spray

我的喷涂休息服务调用其他actor(在构造函数中传递RequestContext)来执行业务逻辑(similar to this approach)。我有一个用例,我需要从文件中读取json文本并返回内容。我希望内容类型是JSON。如何使用requestcontext明确地将内容类型设置为json。

在下面的代码片段中,requestContext需要返回带有Json内容类型的字符串(Json)。的 requestContext.complete( “{\” 名称\ “:\” 约翰\ “}”)

package com.christophergagne.sprayapidemo

import akka.actor.{Actor, ActorRef}
import akka.event.Logging
import akka.io.IO

import spray.routing.RequestContext
import spray.httpx.SprayJsonSupport
import spray.client.pipelining._

import scala.util.{ Success, Failure }

object TimezoneService {
  case class Process(long: Double, lat: Double, timestamp: String)
}

class TimezoneService(requestContext: RequestContext) extends Actor {

  import TimezoneService._

  implicit val system = context.system
  import system.dispatcher
  val log = Logging(system, getClass)

  def receive = {
    case Process(long,lat,timestamp) =>
      process(long,lat,timestamp)
      context.stop(self)
  }

  def process(long: Double, lat: Double, timestamp: String) = { 

    log.info("Requesting timezone long: {}, lat: {}, timestamp: {}", long, lat, timestamp)

    import TimezoneJsonProtocol._
    import SprayJsonSupport._
    val pipeline = sendReceive ~> unmarshal[GoogleTimezoneApiResult[Timezone]]

    val responseFuture = pipeline {
      Get(s"https://maps.googleapis.com/maps/api/timezone/json?location=$long,$lat&timestamp=$timestamp&sensor=false")
    }
    responseFuture onComplete {
      case Success(GoogleTimezoneApiResult(_, _, timeZoneName)) =>
        log.info("The timezone is: {} m", timeZoneName)
        ***requestContext.complete("{\"name\":\"John\"}")***

      case Failure(error) =>
        requestContext.complete(error)
    }
  }
}

谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

如果您需要回复application/json,则应使用以下内容:

respondWithMediaType(MediaTypes.`application/json`) {
     complete { ...
     } 
}

答案 1 :(得分:1)

您需要返回完整的HttpResponse对象而不是简单的字符串。我建议你这样做:

import spray.routing.RequestContext
import spray.http._

requestContext.complete(HttpResponse(StatusCodes.OK, HttpEntity(ContentType(MediaTypes.`application/json`), "{\"name\":\"John\"}")))

您也可以只返回HttpEntity,因为它已定义ToResponseMarshaller,可以找到here。像这样使用它:

import spray.routing.RequestContext
import spray.http._

requestContext.complete(HttpEntity(ContentType(MediaTypes.`application/json`), "{\"name\":\"John\"}"))

我不建议您使用字符串插值来返回JSON,因为这样很难更改响应结构。我建议您使用spray-json库,该库已经定义了ToReponseMarshaller,可以找到here。功能记录为here。您的代码看起来像这样:

import spray.routing.RequestContext
import spray.httpx.marshalling._
import spray.json._
import spray.httpx.SprayJsonSupport._

requestContext.complete(JsObject("name" -> JsString("John")))