Alex K
Alex K

Reputation: 844

Spray client marshalling of custom case class to JSON

I have the following implicits:

object MyJsonProtocol extends DefaultJsonProtocol {
  implicit val impStartObjSys = jsonFormat3(StartObj.Sys)
  implicit val impStartObjData = jsonFormat6(StartObj.Data)
  implicit val impStartObjStart = jsonFormat3(StartObj.Start)
}

It works fine with Spray router and I can normally unmarshall an object into StartObj.Start(that takes a string and sys and data as input parameters)

Now I am trying to write a load test and do JSON requests using the spray-client. Unfortunately it doesn't want to accept my object as an input paramter, error:

[error] Load.scala:85: could not find implicit value for evidence parameter of type >spray.httpx.marshalling.Marshaller[models.StartObj.Start] [error] pipeline(Post(serverHost, newUser)) [error] ^

I started creating a marshaller that would resolve this issue:

  implicit val StartObjMarshaller =
    Marshaller.of[Start](ContentTypes.`application/json`) 
    { (value, contentType, ctx) ⇒ 
       ctx.marshalTo(HttpEntity(contentType, value))
    }

But here it complains about value not being of supported type. It expects only byte array or String. I need String but in Json Format, how should I write this marshaller so that it resolve the issue properly?

Thanks!

Upvotes: 2

Views: 2602

Answers (1)

Alex K
Alex K

Reputation: 844

Ok, I figured this out. I needed to add this import to support json marshalling:

import spray.httpx.SprayJsonSupport._

After that marshalling function would be:

  implicit def StartObjMarshaller[T](implicit writer: RootJsonWriter[T], 
      printer: JsonPrinter = PrettyPrinter) =
  Marshaller.delegate[T, String](ContentTypes.`application/json`) { value ⇒
    val json = writer.write(value)
    printer(json)
  }

Upvotes: 2

Related Questions