在Spray POST路由中将Raw JSON提取为String

Sou*_*nta 9 rest post json scala spray

我有一个POST Spray路由,请求包含一个JSON主体(内容类型"application/json").我想要一种方法从我的路线中的这个请求中提取原始JSON.

对于http:// host:port/somepath/value1我想将post体提取TextMsgResponse.但是对于http:// host:port/somepath/value2我想提取 post体就像一个原始的Json(例如,{ "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          
      } 
    }
   }
Run Code Online (Sandbox Code Playgroud)

moh*_*hit 8

您可以使用extract指令作为

def rawJson = extract { _.request.entity.asString} 
    .
    .
    . 
case "value2" => rawJson{ json =>// use the json 
  } 
Run Code Online (Sandbox Code Playgroud)