How to get query param as HashMap

Martin picture Martin · Mar 4, 2013 · Viewed 10.2k times · Source

I want to be able pass to my server a GET request suh as:

 http://example.com/?a[foo]=1&a[bar]=15&b=3

And when I get the query param 'a', it should be parsed as HashMap like so:

{'foo':1, 'bar':15}

EDIT: Ok, to be clear, here is what I am trying to do, but in Java, instead of PHP:

Pass array with keys via HTTP GET

Any ideas how to accomplish this?

Answer

Tarlog picture Tarlog · Mar 5, 2013

There is no standard way to do that.

Wink supports javax.ws.rs.core.MultivaluedMap. So if you send something like http://example.com/?a=1&a=15&b=3 you will receive: key a values 1, 15; key b value 3.

If you need to parse something like ?a[1]=1&a[gv]=15&b=3 you need to take the javax.ws.rs.core.MultivaluedMap.entrySet() and perform an additional parsing of the keys.

Here's example of code you can use (didn't test it, so it may contain some minor errors):

String getArrayParameter(String key, String index,  MultivaluedMap<String, String> queryParameters) {
    for (Entry<String, List<String>> entry : queryParameters.entrySet()) {
        String qKey = entry.getKey();
        int a = qKey.indexOf('[');
        if (a < 0) {
            // not an array parameter
            continue;
        }
        int b = qKey.indexOf(']');
        if (b <= a) {
            // not an array parameter
            continue;
        }
        if (qKey.substring(0, a).equals(key)) {
            if (qKey.substring(a + 1, b).equals(index)) {
                return entry.getValue().get(0);
            }
        }
    }
    return null;
}

In your resource you should call it like this:

@GET
public void getResource(@Context UriInfo uriInfo) {
    MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
    getArrayParameter("a", "foo", queryParameters);
}