Java: Map 转换为Json
不多逼逼,直接上步骤:
导入依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.4</version>
</dependency>
Map 转换为Json
public class ConvertMapToJson {
public static void main(String[] args) throws IOException {
HashMap<String, Object> hashMap = new HashMap<>();
// 向map中填充数据
hashMap.put("id", 1);
hashMap.put("name", "zhangsan");
hashMap.put("score", 89.2);
// 开始进行转换
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(hashMap);
System.out.println(json);
}
}
转换之后的结果:
Json转换成Map
public class ConvertJsonToMap {
public static void main(String[] args) throws IOException {
String json = "{\"score\":89.2,\"name\":\"zhangsan\",\"id\":1}";
ObjectMapper objectMapper = new ObjectMapper();
Map map = objectMapper.readValue(json, Map.class);
System.out.println(map);
}
}
转换之后的结果:
总结
如果看到这个文章的大佬们,还有什么其他更好的方法。请在下方留言,谢谢!
|