convert URL query String to Map<String,String> - Java java.net

Java examples for java.net:URL Query

Introduction

The following code shows how to convert From String

Demo Code


public class Main{
    public static void main(String[] argv){
        String text = "site=java2s.com;abc=def;";
        System.out.println(convertFromString(text));
    }/*from  w  w w.  j ava 2  s  . c om*/
    public static java.util.Map<String, String> convertFromString(
            String text) {
        java.util.Map<String, String> result = new java.util.LinkedHashMap<String, String>();
        java.util.List<String> keyValuePairs = decode(text, ';');
        for (String pair : keyValuePairs) {
            java.util.List<String> keyAndValue = decode(pair, '=');
            String key = keyAndValue.get(0);
            String value = keyAndValue.get(1);
            result.put(key, value);
        }
        return result;
    }
    public static java.util.List<String> decode(String text, char delimiter) {
        java.util.List<String> parts = new java.util.ArrayList<String>();

        boolean escapeMode = false;
        String part = "";
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            if (c == delimiter) {
                if (escapeMode) {
                    part += delimiter;
                    escapeMode = false;
                } else {
                    // end of part
                    parts.add(part);
                    part = "";
                }
            } else if (c == '\\') {
                if (escapeMode) {
                    part += '\\';
                    escapeMode = false;
                } else {
                    escapeMode = true;
                }
            } else {
                part += c;
            }
        }
        return parts;
    }
   
}

Related Tutorials