Get Json Object using spray.json
Asked Answered
F

1

3

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

Francinefrancis answered 28/2, 2014 at 9:8 Comment(1)
Btw. you usually don't need to use the respondWithMediaType directive. The marshaller will automatically figure out which content type to use.Pusey
C
0

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._
Casta answered 28/2, 2014 at 9:20 Comment(1)
If this is about spray-json it needs an import DefaultJsonProtocol._ and an additional import SprayJsonSupport._ in the routing file.Pusey

© 2022 - 2024 — McMap. All rights reserved.