2

I am trying to set application/json as content-Type in a spray-routing actor. But the content-type i see in my response always is text/plain. I tried using the spray-routing approach ("something") and the spray-can approacch ("something2") but the two routes don't send the response-type properly. Did I miss something?

def receive = runRoute {        
    path("something") {
      get {
        respondWithHeader(`Content-Type`(`application/json`)) {
          complete("""{ "key": "value" }""")
        }
      }
    } ~
    path("something2") {
      get {
        complete(HttpResponse(entity = """{ "key": "value" }""").withHeaders((List(`Content-Type`(`application/json`)))))
      }
    }
  }`enter code here`
Gevatter Tod
  • 131
  • 4
  • I tried to use the code examples from http://stackoverflow.com/questions/19396187/how-do-i-specify-spray-content-type-response-header but they do not work for me – Gevatter Tod Feb 28 '14 at 09:29

2 Answers2

1

It seems that the responseheader is overwritten by the marshaller for string.

Like this it works like a charm:

path("something") {
  get {
    respondWithMediaType(`application/json`) {
      complete("""{ "key": "value" }""")
    }
  }
}
Gevatter Tod
  • 131
  • 4
1

Actually, there is a much better approach to return a json with a application/json content type with spray.json module. If you have just key:value pairs it would be much cleaner to use SprayJsonMarshaller, which would authomatically set appropriate header. Consider the following example:

(get & path("somePath")) { complete(Map("key" -> "value")) }

To make a json response you just need to import two things:

import spray.json.DefaultJsonProtocol._ // contains default marshallers
import spray.httpx.SprayJsonSupport._   // will do all the headers work

If you have your own case class which you would like to send over the wire, then provide a converter into json format:

import spray.json.DefaultJsonProtocol._

case class SomeClass(name: String)
object SomeClass {
  implicit val someClassJson = jsonFormat1(SomeClass.apply)
}

It's a much better approach cause if you later would like to change the format in you response, all you need to do is to change a marshaller, the rewrite your code.

number in the end of jsonFormat method equals to the number of case class arguments.

4lex1v
  • 21,367
  • 6
  • 52
  • 86