Map和JSON之间的转化
Map和JSON之间的转化
1 添加依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency> 复制代码
2 测试
2.1 Map转JSON
//1.map转json @Test public void testJson01(){ //1.Map转JSON Map<String,Object> map=new HashMap<>(); map.put("A","a"); map.put("B","b"); JSONObject jsonObject = new JSONObject(map); System.out.println(jsonObject); } 复制代码
2.2 Map转String
//2.map转Spring @Test public void testJson02(){ Map<String,Object> map=new HashMap<>(); map.put("A","a"); String s = JSONObject.toJSONString(map); System.out.println(s); } 复制代码
2.3 JSON转String
//3.JSON转String @Test public void testJSON03(){ JSONObject json=new JSONObject(); json.put("A","A"); json.put("B","B"); String s = json.toJSONString(); System.out.println(s); } 复制代码
2.4 JSON转Map
//4.JSON转map @Test public void testJSON04(){ JSONObject jsonObject=new JSONObject(); jsonObject.put("A","a"); jsonObject.put("B","b"); Map<String,Object> map= (Map<String,Object>)jsonObject; for(Map.Entry<String,Object> entry:map.entrySet()){ System.out.println(entry.getKey()+"--"+entry.getValue()); } } 复制代码
2.5 String转JSON
//5.String转json @Test public void testJSON05(){ String str="{\"username\":\"abc\",\"pwd\":\"123\"}"; JSONObject json = JSONObject.parseObject(str); Object username = json.get("username"); System.out.println(username); Object pwd = json.get("pwd"); System.out.println(pwd); } 复制代码
作者:用户8400915470232
链接:https://juejin.cn/post/7026997230007484424