您的当前位置:首页正文

使用HuTool将HashMap和ArrayList进行Json的相互转化

2023-05-29 来源:帮我找美食网

前言

在写一个业务时,需要将HashMap转为Json发送,再在别处将接收的Json转为HashMap,在网上搜了半天,最后发现了这个方法,于是记录下来:

过程比较啰嗦,想直接看结果的可以拉到最下面

HashMap 与 Json 的相互转换

首先导入HuTool依赖:

<dependency>
   <groupId>cn.hutool</groupId>
   <artifactId>hutool-all</artifactId>
   <version>5.8.18</version>
</dependency>

我们新建一个测试类,创建一个HashMap:

@SpringBootTest
public class test {

	@Test
	void test(){
		HashMap<String, Integer> map = new HashMap<>();
		map.put("orderId",1);
		map.put("num",1);
	}
}
  • 将HashMap转为Json:
String jsonMap = JSONUtil.toJsonStr(map);
  • 重点来了,再将Json转为HashMap
HashMap<String,Integer> hashMap = JSONUtil.parseObj(jsonMap).toBean(HashMap.class);
  • 输出:
System.out.println("将jsonMap转为hashMap = " + hashMap);
Integer orderId = hashMap.get("orderId");
System.out.println("orderId = " + orderId);
Integer num = hashMap.get("num");
System.out.println("num = " + num);

结果如图所示:

因篇幅问题不能全部显示,请点此查看更多更全内容

热门图文

Top