尝试解析request.queryString,它返回一个Map [String,Seq [String]]
var route = ""
var queryString = "?"
for((k,v) <- request.queryString) {
if(k == "route"){ route = v.head }
else {
queryString += k +"="+ v.head +"&"
}
}
queryString = queryString.substring(0, queryString.length() -1 );
这很好但很有必要。我确信有一种更实用的方法可以做到这一点。有什么帮助吗?
答案 0 :(得分:7)
帮助就在这里!过度评论。
val RouteKey = "route"
val route = request
.getOrElse(RouteKey, Nil) // will return the route, or empty list
.headOption // either Some[head] or None
.getOrElse("") // if None, empty string
val queryString = (request - RouteKey) // remove the route from the request
.map { case (k, v) => // map each key/value pair
k + "=" + v.headOption.getOrElse("") } // into key=value strings
.mkString("?", "&", "") // make that list into a single string
您会注意到我使用相同的模式从列表中安全地获取head
,以处理空列表。如果您发现自己做了很多,那么您可以将该方法添加到Seq[String]
。
implicit def pimpedStringSeq(seq: Seq[String]) = new {
def headStr = seq.headOption.getOrElse("")
}
val RouteKey = "route"
val route = request.getOrElse(RouteKey, Nil).headStr
val queryString = (request - RouteKey).map { case (k, v) => k + "=" + v.headStr }
.mkString("?", "&", "")
答案 1 :(得分:2)
没有那么好,但你可以使用折叠。
import scalaz._
import Scalaz._
request.queryString.foldLeft(("?", "")) { case ((route, queryString), (k, v)) =>
if(k == "route")
(v.head, queryString)
else
(route, queryString + k + "=" + v.head + "&")
} :-> (_.init)
那个可爱的微笑操作符(:->
)用于转换我们在折叠结束时得到的2元组的第二个元素。它可以理解如下:
t :-> f == (t._1, f(t._2))
您可以看到来源here。
来自控制台的示例:
scala> val requestQueryString = Map("route" -> Seq("a"), "foo" -> Seq("b"), "bar" -> Seq("c"))
requestQueryString: scala.collection.immutable.Map[java.lang.String,Seq[java.lang.String]] = Map(route -> List(a), foo -
> List(b), bar -> List(c))
scala> var route = ""
var queryString = "?"
for((k,v) <- requestQueryString) {
if(k == "route"){ route = v.head }
else {
queryString += k +"="+ v.head +"&"
}
}
queryString = queryString.substring(0, queryString.length() -1 );
route: java.lang.String = a
queryString: java.lang.String = ?foo=b&bar=c
queryString: java.lang.String = ?foo=b&bar=c
scala> requestQueryString.foldLeft(("?", "")) { case ((queryString, route), (k, v)) =>
if(k == "route")
(queryString, v.head)
else
(queryString + k + "=" + v.head + "&", route)
}
res8: (java.lang.String, java.lang.String) = (?foo=b&bar=c&,a)
scala> ((_: String).init) <-: res8
res9: (String, java.lang.String) = (?foo=b&bar=c,a)
scala> requestQueryString.foldLeft(("?", "")) { case ((route, queryString), (k, v)) =>
if(k == "route")
(v.head, queryString)
else
(route, queryString + k + "=" + v.head + "&")
} :-> (_.init)
res10: (java.lang.String, String) = (a,foo=b&bar=c)