mapStringMapStringObjecttostring转成map
无法直接将字符串转换为Map<String, Map<String, Object>>,因为该字符串表示的是一个对象的字符串形式,需要先将其转换为对象,再将对象转换为Map。
可以使用JSON库将字符串转换为对象,然后将对象转换为Map。具体实现代码如下:
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Map;
public class StringToMapConverter {
public static Map<String, Map<String, Object>> convert(String str) throws IOException {
ObjectMapper mapper = new ObjectMapper();
TypeReference<Map<String, Map<String, Object>>> typeRef =
new TypeReference<Map<String, Map<String, Object>>>() {};
return mapper.readValue(str, typeRef);
}
}
使用示例:
String str = "{\"key1\":{\"key2\":\"value2\"}}";
Map<String, Map<String, Object>> map = StringToMapConverter.convert(str);
System.out.println(map); // output: {key1={key2=value2}}
原文地址: https://www.cveoy.top/t/topic/baB1 著作权归作者所有。请勿转载和采集!