java 的 Map<String,Object> 转 MultiValueMap<String,String>
时间: 2023-11-11 20:11:02 浏览: 358
可以使用Spring框架中的MultiValueMapConverter进行转换。具体实现代码如下:
```java
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import java.util.Map;
public class MapToMultiValueMapConverter implements Converter<Map<String, Object>, MultiValueMap<String, String>> {
@Override
public MultiValueMap<String, String> convert(Map<String, Object> source) {
MultiValueMap<String, String> result = new LinkedMultiValueMap<>();
for (Map.Entry<String, Object> entry : source.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof String) {
result.add(key, (String) value);
} else if (value instanceof String[]) {
String[] values = (String[]) value;
for (String v : values) {
result.add(key, v);
}
} else if (value instanceof Iterable) {
Iterable iterable = (Iterable) value;
for (Object v : iterable) {
result.add(key, String.valueOf(v));
}
} else {
result.add(key, String.valueOf(value));
}
}
return result;
}
}
```
使用方式如下:
```java
Map<String, Object> map = new HashMap<>();
map.put("name", "张三");
map.put("age", 18);
map.put("hobbies", new String[]{"reading", "swimming"});
map.put("favorite_books", Arrays.asList("Java编程思想", "Effective Java"));
MultiValueMap<String, String> multiValueMap = new MapToMultiValueMapConverter().convert(map);
```
这样就可以将Map对象转换为MultiValueMap对象了。
阅读全文