1

I want to parse the following:

full_uri= "path/for/uri?$param1=value1&$param2=value2

in a way that gives me the uri as a string and the parameters as a map. What I'm trying right now is:

String[] full_uri_split = full_uri.split("\\?");
String uri = full_uri_split[0];
String parameters = full_uri_split[1];

This gives me 2 variables, 1 that is the uri, and another that is a string containing all the parameters, in the format of:

parameters = "$param1=value1&$param2=value2"

My next best guess is to then split it on the & signs:

String parameters_split = parameters.split("&");

which returns:

["$param1=value1", "$param2=value2"]

Now I want to convert this into a Map that looks like so:

"param1":"value1",
"param2":"value2"

and I'm not sure how to go about it.

I'm sure I could get it to work by doing more splits, but it seems horribly inefficient. So essentially, I want to turn:

full_uri = "path/for/uri?$param1=value1&$param2=value2"

into

uri = "path/for/uri"
params = {
    "param1": "value1",
    "param2": "value2"
}
user2869231
  • 1,431
  • 5
  • 24
  • 53
  • 3
    Possible duplicate of [Parse the Uri string into name-value collection in java](http://stackoverflow.com/questions/13592236/parse-the-uri-string-into-name-value-collection-in-java) – Marcinek Dec 16 '15 at 21:59
  • 1
    Parameter names can be duplicated in URI. "path/for/uri?p=1&p=2" is a valid URI. –  Dec 16 '15 at 22:07

1 Answers1

1

Here is a solution using a loop.

Map<String, String> params = new HashMap<>();
for (String s : parameters_split){
    params.put(s.split("=")[0], s.split("=")[1]);
}
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89