Extracting Raw JSON as String inside a Spray POST route
Asked Answered
C

1

9

I've a POST Spray route and the request contains a JSON body (content-type "application/json"). I want a way to extract the raw JSON from this request inside my route.

For http://host:port/somepath/value1 I want to extract the post body as TextMsgResponse. But for http://host:port/somepath/value2 I want to extract the post body just as a raw Json (e.g., { "name":"Jack", "age":30 }

val myRoute = path("somepath" / Segment) { pathSegment => 
post {   //use only POST requests
  pathSegment match {
    case "value1" =>
      entity(as[TextMsgResponse]) { textMsg =>
        complete {
          //do something with the request
          StatusCodes.OK
        }
      } 
    case "value2" => { 
       //here is I want to extract the RAW JSON from the request          
      } 
    }
   }
Comeau answered 29/1, 2015 at 13:20 Comment(2)
Have you tried entity(as[Array[Byte]]) or entity(as[String])?Launalaunce
Yes and both of them don't work.Comeau
J
8

You can use the extract directive as

def rawJson = extract { _.request.entity.asString} 
    .
    .
    . 
case "value2" => rawJson{ json =>// use the json 
  } 
Jagatai answered 29/1, 2015 at 17:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.