Map和JSON之间的转化
1 添加依赖
< dependency> < groupId> com.alibaba</ groupId> < artifactId> fastjson</ artifactId> < version> 1.2.47</ version> </ dependency>
2 测试
2.1 Map转JSON
@Test public void testJson01 ( ) { 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
@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
@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
@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
@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) ; }
2.6List<String,Objet>转成jsonArray
List<Map<String,Object>> list=new LinkedList<>();for(int i=0;i<10;i++){Map<String,Object> map=new HashMap<>();map.put("a"+i,"a");list.add(map);}JSONArray jsonArray= (JSONArray) JSONArray.toJSON(list);System.out.println(jsonArray.size());