java中 map和 json 字符串 互转

2023-12-15 05:10:11

依赖包:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency>

包:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

将 map 转换为 json 字符串

public static void main(String[] args) throws JsonProcessingException {
    Map<String,Object> map = new HashMap<>();
    map.put("name","zs");
    map.put("age",18);

    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(map);
    System.out.println(json); // {"name":"zs","age":18}
}

将 json 转换为 map

public static void main(String[] args) throws JsonProcessingException {
    Map<String,Object> map = new HashMap<>();
    map.put("name","zs");
    map.put("age",18);

    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(map);
    System.out.println(json); // {"name":"zs","age":18}

    // 将字符串转为 map 
    Map<String,Object> map1 = mapper.readValue(json, Map.class);
    System.out.println(map1.get("name")); // zs
}

文章来源:https://blog.csdn.net/weixin_46047612/article/details/134996625
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。