JSON-Lib方式
/**
* 函数注释:parseJSON2Map()<br>
* 用途:该方法用于json数据转换为<Map<String, Object>
* @param jsonStr
* @return
*/
public static Map<String, Object> parseJSON2Map(String jsonStr){
Map<String, Object> map = new HashMap<String, Object>();
//最外层解析
JSONObject json = JSONObject.fromObject(jsonStr);
for(Object k : json.keySet()){
Object v = json.get(k);
//如果内层还是数组的话,继续解析
if(v instanceof JSONArray){
List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
Iterator<JSONObject> it = ((JSONArray)v).iterator();
while(it.hasNext()){
JSONObject json2 = it.next();
list.add(parseJSON2Map(json2.toString()));
}
map.put(k.toString(), list);
} else {
map.put(k.toString(), v);
}
}
return map;
}
/**
* 函数注释:parseJSON2MapString()<br>
* 用途:该方法用于json数据转换为<Map<String, String><br>
*/
public static Map<String, String> parseJSON2MapString(String jsonStr){
Map<String, String> map = new HashMap<String, String>();
//最外层解析
JSONObject json = JSONObject.fromObject(jsonStr);
for(Object k : json.keySet()){
Object v = json.get(k);
if(null!=v){
map.put(k.toString(), v.toString());
}
}
return map;
}
Jackson方式
/**
* Map转换JSON
* @param map
* @return
* @throws Exception
*/
public static String mapConvert2JSON(Map map) throws Exception{
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(map);
}
/**
* JSON 转换 Map
* @param json
*/
public static Map readJson2Map(String json) throws Exception{
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Map<String, Object>> maps = objectMapper.readValue(json, Map.class);
/*Set<String> key = maps.keySet();
Iterator<String> iter = key.iterator();
while (iter.hasNext()) {
String field = iter.next();
System.out.println(field + ":" + maps.get(field));
}*/
return maps;
}
本段代码来自 http://www.ibloger.net/article/2470.html