Skip to content

Instantly share code, notes, and snippets.

@kazuya-k-ishibashi
Created November 27, 2017 22:16
Show Gist options
  • Save kazuya-k-ishibashi/88ac55257cd53bfa33b908b32a9577b9 to your computer and use it in GitHub Desktop.
Save kazuya-k-ishibashi/88ac55257cd53bfa33b908b32a9577b9 to your computer and use it in GitHub Desktop.
querystring parser.
package dev.kishibashi.common.module.querystring;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author kishibashi
*/
public class QS {
private final Map<String, Object> map = new LinkedHashMap<>();
public QS(final String query) {
final Map<String, List<String>> tempMap = new LinkedHashMap<>();
for (String keyValue: query.replaceFirst("^\\?", "").split("&")) {
final String[] sp_1 = keyValue.split("=");
final String key = sp_1[0];
final String value = (sp_1.length >= 1) ? sp_1[1] : null;
final String[] sp_2 = key.split("\\[|\\]");
final String keyName = sp_2[0];
final Integer index = (sp_2.length >= 1) ? Integer.parseInt(sp_2[1]) : null;
if (!tempMap.containsKey(keyName)) {
tempMap.put(keyName, new ArrayList<>());
}
final List<String> valueList = tempMap.get(keyName);
if (index == null) {
valueList.add(value);
continue;
}
while (valueList.size() < index) {
valueList.add(null);
}
valueList.add(index, value);
}
for (Map.Entry<String, List<String>> entry: tempMap.entrySet()) {
final List<String> valueList = entry.getValue();
final Object value = (valueList.size() >= 2) ? valueList : valueList.get(0);
map.put(entry.getKey(), value);
}
}
public Map<String, Object> toMap() {
return map;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment