1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
import cn.hutool.core.net.url.UrlQuery; import com.fasterxml.jackson.core.type.TypeReference; import lombok.experimental.UtilityClass; import org.dromara.streamquery.stream.core.collection.Maps; import org.dromara.streamquery.stream.core.stream.Steam;
import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Objects;
import static org.dromara.streamquery.stream.core.stream.collector.Collective.entryToMap;
@UtilityClass public class ParamUtil {
public static Map<String, String> getParamMapFrom(String param) { var queryMap = UrlQuery.of(param, StandardCharsets.UTF_8).getQueryMap(); return Steam.of(queryMap) .map(e -> Maps.entry(String.valueOf(e.getKey()), String.valueOf(e.getValue()))) .collect(entryToMap()); }
public static Map<String, String> getParamMapFrom(URI uri) { return getParamMapFrom(uri.getQuery()); }
public static String toParamStr(Object object) { Map<String, Object> map = JsonUtils.mapper.convertValue(object, new TypeReference<>() { }); Map<String, String> resultMap = new HashMap<>(); buildQueryMap("", map, resultMap); return Steam.of(resultMap) .map(entry -> entry.getKey() + "=" + entry.getValue()) .join("&"); }
private static void buildQueryMap(String str, Object value, Map<String, String> resultMap) { if (value instanceof Map) { ((Map<?, ?>) value).forEach((k, v) -> { String newPrefix = str.isEmpty() ? k.toString() : str + "." + k; buildQueryMap(newPrefix, v, resultMap); }); } else if (value instanceof Iterable<?>) { Steam.of((Iterable<?>) value).forEachIdx((item, index) -> { String newPrefix = String.format("%s[%d]", str, index); buildQueryMap(newPrefix, item, resultMap); }); } else { resultMap.put(str, Objects.toString(value, "")); } } }
|