Map与JSON之间转换

                //Map转换成JSON
Map map = new HashMap(); map.put("a","aaa"); map.put("b","bbb"); map.put("c","ccc"); String json=JSON.toJSONString(map); System.out.println(json);//输出{"a":"aaa","b":"bbb","c":"ccc"}

//JSON转换成Map

Map map1 = JSON.parseObject(json);System.out.println(map1.get("a"));for (Object mapData : map.entrySet()) {Map.Entry entry = (Map.Entry)mapData;System.out.println(entry.getKey()+"--->"+entry.getValue());}/*输出b--->bbbc--->ccca--->aaa*/

map中含有对象Map -> JSON

//Map -> JSONMap map = new HashMap(); map.put("a",new Bar()); map.put("b",new Bar()); map.put("c",new Bar()); String json = JSON.toJSONString(map,true); System.out.println(json); /*输出{ "a":{  "barAge":383687382,  "barDate":1494945882018,  "barName":"name_1689176802" }, "b":{  "barAge":-100528778,  "barDate":1494945882018,  "barName":"name_-878176366" }, "c":{  "barAge":-344075192,  "barDate":1494945882018,  "barName":"name_-1710740534" }}*/

//JSON -> Map

Map map1 = (Map)JSON.parse(json); for (String key : map1.keySet()) { System.out.println(key+":"+map1.get(key)); } /*输出b:{"barAge":-100528778,"barDate":1494945882018,"barName":"name_-878176366"}c:{"barAge":-344075192,"barDate":1494945882018,"barName":"name_-1710740534"}a:{"barAge":383687382,"barDate":1494945882018,"barName":"name_1689176802"}*/


来自:http://www.cnblogs.com/DreamDrive/p/5778959.html

           

你可能感兴趣的:(Map与JSON之间转换)