###Map<String, Object> 转 Json (Android环境)
public void onButtonClick(View view){
Map<String, Object> map = new HashMap<>();
Map<String, Object> map0 = new HashMap<>();
map0.put("q","1");
map0.put("w","2");
map0.put("e","3");
List<Object> stringList = new ArrayList<>();
stringList.add(map0);
stringList.add(map0);
stringList.add(map0);
Map<String, Object> map1 = new HashMap<>();
map1.put("j","1");
map1.put("k","2");
map1.put("l","3");
map1.put("m",stringList);
map.put("a", "1");
map.put("b", "2");
map.put("c", "3");
map.put("stringList", stringList);
map.put("map", map1);
try {
Log.d(TAG, mapToJson(map));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 将Map转换成Json
* @param jsonMap
* @return
* @throws Exception
*/
public String mapToJson( Map<String, Object> jsonMap ) throws Exception{
StringBuilder result = new StringBuilder();
result.append("{");
Iterator<Map.Entry<String, Object>> entryIterator = jsonMap.entrySet().iterator();
for(Map.Entry<String, Object> entry : jsonMap.entrySet()){
String key = entry.getKey();
Object value = entry.getValue();
if(value instanceof Map){
System.out.println("\n Object Key : "+key);
String mapJson = mapToJson((Map<String, Object>) value);
result.append("\"").append(key).append("\":").append(mapJson);
} else if(value instanceof List){
System.out.println("\n Array Key : "+key);
String listJson = listToJson((List) value);
result.append("\"").append(key).append("\":").append(listJson);
}else{
System.out.println("key : "+key+" value : "+value);
result.append("\"").append(key).append("\":\"").append(value).append("\"");
}
// 最后一个去掉 逗号
entryIterator.next();
if(entryIterator.hasNext()){
result.append(",");
}
}
result.append("}");
return result.toString();
}
/**
* 将List转成Json
* @param jsonList
* @return
* @throws Exception
*/
public String listToJson( List jsonList ) throws Exception {
StringBuilder result = new StringBuilder();
result.append("[");
JSONArray jsonArray = new JSONArray(jsonList);
for ( int i = 0; i < jsonArray.length(); i++ ) {
if ( jsonArray.opt(i) instanceof JSONObject) {
String mapJson = mapToJson((Map<String, Object>)jsonList.get(i));
result.append(mapJson);
}else if ( jsonArray.opt(i) instanceof JSONArray ) {
String listJson = listToJson((List) jsonList.get(i));
result.append(listJson);
}else {
result.append("\"").append(jsonArray.opt(i)).append("\"");
}
// 最后去掉 逗号
if(i < jsonArray.length()-1){
result.append(",");
}
}
result.append("]");
return result.toString();
}