将查询字符串转换为scala中的映射

我有一个这种形式的查询字符串:

val query = "key1=val1&key2=val2&key3=val3

我想创建一个包含上述键/值对的地图.到目前为止,我这样做:

//creating an iterator with 2 values in each group. Each index consists of a key/value pair
val pairs = query.split("&|=").grouped(2)

//inserting the key/value pairs into a map
val map = pairs.map { case Array(k, v) => k -> v }.toMap

这样做有什么问题吗?如果是这样,我可以使用一些库吗?

最佳答案 以下是使用 URLEncodedUtils的方法:

import java.net.URI

import org.apache.http.client.utils.URLEncodedUtils
import org.apache.http.{NameValuePair => ApacheNameValuePair}

import scala.collection.JavaConverters._
import scala.collection.immutable.Seq

object GetEncodingTest extends App {
  val url = "?one=1&two=2&three=3&three=3a"
  val params = URLEncodedUtils.parse(new URI(url), "UTF_8")

  val convertedParams: Seq[ApacheNameValuePair] = collection.immutable.Seq(params.asScala: _*)
  val scalaParams: Seq[(String, String)] = convertedParams.map(pair => pair.getName -> pair.getValue)
  val paramsMap: Map[String, String] = scalaParams.toMap
  paramsMap.foreach(println)
}
点赞