有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

http反序列化响应正文,并在Java中列出多个“list[]”参数

我想解析HTTP响应体,其格式如下: list[]=a&list[]=b&list[]=c&list[]=d&list[]=e(可能有不同数量的元素) 到List<String>

我可以用&分割字符串并切断list[]=,但我想知道是否有更优雅的方法来实现这一点(某种库能够将其反序列化为列表)


共 (1) 个答案

  1. # 1 楼答案

    I could just split the string by & and cut off list[]= [...]

    你肯定能做到。只需记住URL-decode拆分查询字符串后的参数;)

    [...] but I wonder if there is some more elegant way to do this (some kind of library that is able to deserialize it to List)

    如果您正在寻找库,可以使用Apache的^{}

    String queryString = "list[]=a&list[]=b&list[]=c&list[]=d&list[]=e";
    
    List<NameValuePair> valuePairs = URLEncodedUtils.parse(queryString, StandardCharsets.UTF_8);
    Map<String, List<String>> queryParams = valuePairs.stream()
            .collect(groupingBy(NameValuePair::getName, mapping(NameValuePair::getValue, toList())));
    
    List<String> strings = queryParams.get("list[]");