convert URL query String to Map - Java java.net

Java examples for java.net:URL Query

Description

convert URL query String to Map

Demo Code


public class Main{

    public static void main(String[] argv){
        String text = "java2s.com=tutorial;a=0";
        System.out.println(convertFromString(text));
    }/* w ww .j a  v a2  s.  co  m*/
    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