① pom依赖:
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.8</version></dependency>
② 在 Jackson 中,我们可以使用mapper.readValue(json, Map.class)
将 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 JacksonMapExample1 {public static void main(String[] args) {ObjectMapper mapper = new ObjectMapper();String json = "{\"name\":\"mkyong\", \"age\":\"37\"}";try {// convert JSON string to MapMap<String, String> map = mapper.readValue(json, Map.class);System.out.println(map);// it worksMap<String, String> map1 = mapper.readValue(json, new TypeReference<Map<String, String>>() {});System.out.println(map1);} catch (IOException e) {e.printStackTrace();}}}
输出:
{name=mkyong, age=37}{name=mkyong, age=37}