MJavaDev
MJavaDev

Reputation: 271

Deserialize response body with multiple "list[]" parameters to List in Java

I would like to parse HTTP response body which is in following format: list[]=a&list[]=b&list[]=c&list[]=d&list[]=e (there might be different number of elements) to List<String>

I could just split the string by & and cut off list[]=, 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)

Upvotes: 0

Views: 168

Answers (1)

cassiomolin
cassiomolin

Reputation: 130977

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

You surely could do it. Just remember to URL-decode the parameters after splittig the query string ;)

[...] 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)

If you are looking for a library, you could use Apache's URLEncodedUtils:

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[]");

Upvotes: 1

Related Questions