spray-json cannot marshal Map[String,String]
Asked Answered
R

1

10

I have the following route setup, but when my map is returned in the first complete block I get an error:

could not find implicit value for evidence parameter of type spray.httpx.marshalling.Marshaller[scala.collection.immutable.Map[String,String]]

import spray.routing.HttpService
import akka.actor.Actor
import spray.http.HttpRequest
import spray.routing.RequestContext
import spray.json.DefaultJsonProtocol._


class UserServiceActor extends Actor with RestUserService {
  def actorRefFactory = context
  def receive = runRoute(linkRoute)

}

trait RestUserService extends HttpService {

  val userService = new LinkUserService

  def linkRoute = 
    pathPrefix("user" / Segment) {
      userId =>
        path("link") {
          parameters('service ! "YT") {
            complete {
              Map("status"-> "OK", "auth_url" -> "http://mydomain.com/auth")
            }
          }
        }
    }
}

According to this test I should be able to convert a Map to json when DefaultJsonProtocol._ is imported but even that's failing:

val map:Map[String, String] = Map("hi"->"bye")
map.toJson

Cannot find JsonWriter or JsonFormat type class for scala.collection.mutable.Map[String,String]

Not sure what's wrong :(

Roturier answered 11/9, 2013 at 20:40 Comment(0)
R
22

Someone on the spray mailing list pointed out that the Map being created was a mutable one, spray-json won't marshal that. I changed it to be scala.collection.immutable.Map and also added the following imports:

import spray.httpx.SprayJsonSupport._
import spray.json.DefaultJsonProtocol._

And now everything works great.

Roturier answered 13/9, 2013 at 18:13 Comment(2)
OMG. After 30min of digging through the Internet finally a solution that is up to date with spray API changes. Thank you! Without the imports I was not able to marshall JSObject.Parkin
@PawelSzulc i feel the sameSmile

© 2022 - 2024 — McMap. All rights reserved.