Search code examples
scalasprayspray-json

How to perform a simple json post with spray-json in spray?


I'm trying to perform a simple json post with spray. But it seems that i can get an http entity for a json object that can be Marshall.

here is my error:

[error] ...../IdeaProjects/PoolpartyConnector/src/main/scala/org/iadb/poolpartyconnector/thesaurusoperation/ThesaurusCacheService.scala:172: could not find implicit value for evidence parameter of type spray.httpx.marshalling.Marshaller[spray.json.JsValue]

[error] val request = Post(s"$thesaurusapiEndpoint/$coreProjectId/suggestFreeConcept?", suggestionJsonBody)

and the code that comes with it:

 override def createSuggestedFreeConcept(suggestedPrefLabel: String, lang: String, scheme: String, b: Boolean): String = {

    import system.dispatcher
    import spray.json._

    val pipeline      = addCredentials(BasicHttpCredentials("superadmin", "poolparty")) ~> sendReceive


    val label              = LanguageLiteral(suggestedPrefLabel, lang)
    val suggestion         = SuggestFreeConcept(List(label), b, Some(List(scheme)), None, None,None, None)
    val suggestionJsonBody = suggestion.toJson

    val request            = Post(s"$thesaurusapiEndpoint/$coreProjectId/suggestFreeConcept?", suggestionJsonBody)

    val res                = pipeline(request)

    getSuggestedFromFutureHttpResponse(res) match {

      case None => ""
      case Some(e) => e

    }
  }

Please, does any one has an idea of what is going on with the implicit marshaller. I though spray Json would come with implicit marshaller.


Solution

  • Here is how i solved it:

    override def createSuggestedFreeConcepts(suggestedPrefLabels: List[LanguageLiteral], scheme: String, checkDuplicates: Boolean): List[String] = {
    
    
        import system.dispatcher
    
        import spray.httpx.marshalling._
        import spray.httpx.SprayJsonSupport._
    
        val pipeline      = addCredentials(BasicHttpCredentials("superadmin", "poolparty")) ~> sendReceive
    
    
        suggestedPrefLabels map { suggestedPrefLabel =>
    
          val suggestion    = SuggestFreeConcept(List(suggestedPrefLabel), checkDuplicates, Some(List(Uri(scheme))), None, None, None, None)
          val request       = Post(s"$thesaurusapiEndpoint/$coreProjectId/suggestFreeConcept", marshal(suggestion))
    
          val res           = pipeline(request)
    
          getSuggestedFromFutureHttpResponse(res) match {
    
            case None => ""
            case Some(e) => e
    
          }
    
        }
    
      }
    

    the key is:

    import spray.httpx.marshalling._ import spray.httpx.SprayJsonSupport._

    and

    val request = Post(s"$thesaurusapiEndpoint/$coreProjectId/suggestFreeConcept", marshal(suggestion))

    I marshall suggestion. The explanation is not super super straightforward. But by fetching around in the doc, it is explained.