JSON与MAP之间的转换

来源:互联网 发布:交付软件需提供 编辑:程序博客网 时间:2024/05/21 08:12
引用jar包:点击下载

代码如下:

[html] view plain copy
  1. import java.util.ArrayList;  
  2. import java.util.HashMap;  
  3. import java.util.Iterator;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6. import java.util.Set;  
  7.   
  8. import net.sf.json.JSONArray;  
  9. import net.sf.json.JSONObject;  
  10.   
  11. public class JsonMapUtil {  
  12.     @SuppressWarnings("unchecked")  
  13.     public static Map<String, Object> Json2Map(String jsonStr){    
  14.         Map<String, Object> map = new HashMap<String, Object>();    
  15.         //最外层解析    
  16.         JSONObject json = JSONObject.fromObject(jsonStr);    
  17.         for(Object k : json.keySet()){    
  18.             Object v = json.get(k);     
  19.             //如果内层还是数组的话,继续解析    
  20.             if(v instanceof JSONArray){    
  21.                 List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();    
  22.                 Iterator<JSONObject> it = ((JSONArray)v).iterator();    
  23.                 while(it.hasNext()){    
  24.                     JSONObject json2 = it.next();    
  25.                     list.add(Json2Map(json2.toString()));    
  26.                 }    
  27.                 map.put(k.toString(), list);    
  28.             } else {    
  29.                 map.put(k.toString(), v);    
  30.             }    
  31.         }    
  32.         return map;    
  33.     }   
  34.       
  35.     public static JSONObject map2Json(Map<String,Object> map){  
  36.         JSONObject json = new JSONObject();  
  37.         Set<String> set = map.keySet();  
  38.         for (Iterator<String> it = set.iterator();it.hasNext();) {  
  39.             String key = it.next();  
  40.             json.put(key, map.get(key));  
  41.         }         
  42.         return json;  
  43.     }  
  44.       
  45.     public static void main(String[] args) {  
  46.         JSONObject json = new JSONObject();  
  47.         JSONObject json2 = new JSONObject();  
  48.         json2.put("json", "json");  
  49.         json2.put("json2", "json2");  
  50.         JSONArray ja = new JSONArray();  
  51.         ja.add(json2);  
  52.         json.put("id", ja);  
  53.         json.put("name", "{\"33\",\"ddssa\"}");  
  54.         json.put("age", "s2dee");  
  55.         System.out.println(Json2Map(json.toString()));  
  56.           
  57.         Map<String, Object> map = new HashMap<String, Object>();  
  58.         map.put("id", "sdeee");  
  59.         map.put("name", "{\"name1\":\"xiaoming\",\"name2\":\"daming\",}");  
  60.         map.put("age", "s2dee");  
  61.         System.out.println(map2Json(map));  
  62.     }  
  63. }  
测试结果:

[html] view plain copy
  1. MAP:{id=[{json=jsonjson2=json2}], age=s2deename={"33","ddssa"}}  
  2. JSON:{"id":"sdeee","age":"s2dee","name":{"name1":"xiaoming","name2":"daming"}}  
原创粉丝点击