I have a string url like this:
exampleUrl = www.example.com/test?item=param1=1¶m2=11¶m3=111&item=param1=2¶m2=22¶m3=222
and i want to extract from it a Map of key values using item as key.
I wrote the below function
fun String.getUrlParams(): Map<String, List<String>> {
val params = HashMap<String, List<String>>()
val urlParts = this.split("\\?".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
if (urlParts.size > 1) {
val query = urlParts[1]
for (param in query.split("item=".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) {
System.out.println(param)
val key = "item"
var value = URLDecoder.decode(param, "UTF-8")
var values: MutableList<String>? = params[key] as MutableList<String>?
if (values == null) {
values = ArrayList()
params[key] = values as ArrayList<String>
}
values?.add(value)
}
}
return params
}
But on printed data i am getting this -> {item=[, param1=1¶m2=11¶m3=111&, param1=2¶m2=22¶m3=222]}. It has an empty value on start and the & symbol on the end of second value.
The correct one should be -> {item=[param1=1¶m2=11¶m3=111, param1=2¶m2=22¶m3=222]}
What am i missing? Thanks in advance