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

时间:2015-01-29 13:20:47

标签: json scala rest post spray

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

对于http://host:port/somepath/value1,我想提取帖子正文为TextMsgResponse。但对于http://host:port/somepath/value2,我想提取帖子正文,就像原始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          
      } 
    }
   }

1 个答案:

答案 0 :(得分:8)

您可以将extract指令用作

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