How to parse query parameter efficiently in java?

All I have is the request URI from which I have to parse the request parameters. What I am doing is add them to json / hashmap and get it again like below.

String requestUri = "name=raju&school=abcd&college=mnop&color=black&fruit=mango";

      

All I have to do is finally assign the variables like this:

String name = "raju";
String school = "abcd";
String college = "mnop";
String color = "black";
String fruit = "mango";

      

So I parse the uri request like this

String[] paramsKV = requestUri.split("&");
JSONArray jsonKVArr = new JSONArray();
for (String params : paramsKV) {
    String[] tempArr = params.split("=");
    if(tempArr.length>1) {
        String key = tempArr[0];
        String value = tempArr[1];
        JSONObject jsonObj = new JSONObject();
        jsonObj.put(key, value);
        jsonKVArr.put(jsonObj);
     }
 }

      

Another way is to fill in the same in the hash map and get the same. Another way is to match the string requestUri

against a regex pattern and get the results.

Let's say, to get a value school

, I need to match values ​​between the starting point of a string school

and the next &

- which is not very good.

  • What is the best approach to parsing a String query in java?
  • How could I better deal with this?

I need to plot another hash map like from the above results, for example

Map<String, String> resultMap = new HashMap<String, String>;

resultMap.put("empname", name);
resultMap.put("rschool", school);
resultMap.put("empcollege", college);
resultMap.put("favcolor", color);
resultMap.put("favfruit", fruit);

      

To keep things simple, all I have to do is parse the request parameter and build a hashMap, naming the key

filed differently. How can I do this in an easy way? Any help on this is greatly appreciated.

+3


source to share


4 answers


Here's another possible solution:



    Pattern pat = Pattern.compile("([^&=]+)=([^&]*)");
    Matcher matcher = pat.matcher(requestUri);
    Map<String,String> map = new HashMap<>();
    while (matcher.find()) {
        map.put(matcher.group(1), matcher.group(2));
    }
    System.out.println(map);

      

+1


source


Use the jackson json parser. Maven dependency:

<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.5.3</version>
        </dependency>

      



Now use ObjectMapper to create a map from json string:

ObjectMapper mapper = new ObjectMapper();
Map list = mapper.readValue(requestUri, Map.class);

      

+1


source


You can use Java 8 and store your data in HashMap in one operation.

Map<String,String> map = Pattern.compile("\\s*&\\s*")
                .splitAsStream(requestUri.trim())
                .map(s -> s.split("=", 2))
                .collect(Collectors.toMap(a -> a[0], a -> a.length > 1 ? a[1]: ""));

      

+1


source


Short answer: every HTTP client library will do it for you. Example: https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URLEncodedUtils.html#parse(java.lang.String,%20java.nio.charset .Charset)

They basically approach him the same way. The key-value pair is constrained &

and the keys are from values =

, so String split

is fine for both.

From what I can tell, however, your hashmap inserts map new keys to existing values, so there is no optimism, except maybe switching to Java 8 Stream for readability / maintenance and / or discarding the original jsonArray and mapping directly to the hashmap.

+1


source







All Articles