Java json字符串 转 mapper 再取出键值对
时间: 2023-10-30 10:08:08 浏览: 82
Java 把json对象转成map键值对的方法
在 Java 中,可以使用 Jackson 库将 JSON 字符串转换为 Java 对象(mapper),然后再从 mapper 中取出键值对。具体操作步骤如下:
1. 引入 Jackson 库
```xml
<!-- pom.xml 文件中 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
```
2. 将 JSON 字符串转换为 mapper
```java
import com.fasterxml.jackson.databind.ObjectMapper;
String jsonString = "{\"name\":\"Tom\",\"age\":20}";
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(jsonString, Map.class);
```
3. 从 mapper 中取出键值对
```java
String name = (String) map.get("name");
int age = (int) map.get("age");
System.out.println("姓名:" + name);
System.out.println("年龄:" + age);
```
完整代码如下:
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
public class JsonMapperDemo {
public static void main(String[] args) throws Exception {
String jsonString = "{\"name\":\"Tom\",\"age\":20}";
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(jsonString, Map.class);
String name = (String) map.get("name");
int age = (int) map.get("age");
System.out.println("姓名:" + name);
System.out.println("年龄:" + age);
}
}
```
阅读全文