在 Spray POST 路由中将 Raw JSON 提取为字符串

Extracting Raw JSON as String inside a Spray POST route

我有一个 POST Spray 路线并且请求包含一个 JSON body (content-type "application/json")。我想要一种方法从我的路线中的这个请求中提取原始 JSON 。

对于 http://host:port/somepath/value1 I want to extract the post body as TextMsgResponse. But for http://host:port/somepath/value2 我想 提取 post body 就像原始 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          
      } 
    }
   }

您可以将 extract 指令用作

def rawJson = extract { _.request.entity.asString} 
    .
    .
    . 
case "value2" => rawJson{ json =>// use the json 
  }