Get Json Object using spray.json

2019-05-10 14:55发布

问题:

I'm using spray and I need to return a json object through a method.

val route = 

path("all-modules") {
        get {
          respondWithMediaType(`text/html`) {
            complete( configViewer.findAllModules.toString)
          }
        }
      }

This prints ConfigResults(S1000,Success,List(testDataTypes, mandate, sdp))

But I need get this as the json object. how can I do it?

I tried in this way

 val route =

    path("all-modules") {
      get {
        respondWithMediaType(`application/json`) {
          complete{
            configViewer.findAllModules
          }
        }
      }
    }

It gives an compilation error could not find implicit value for parameter marshaller: spray.httpx.marshalling.ToResponseMarshaller

回答1:

You need to tell Spray how it should serialize your case class.

Just configure something like

object JsonSupport {
    implicit val formatConfigResults = jsonFormat3(ConfigResults)
}

The number in jsonFormat'number' stands for the number of members in your case class.

Then you just need to import into your route, the class where you define this implicit.

import JsonSupport._