好像没有什么特别的办法,可能是我才疏学浅,
我知道的两种方式:
map是键值对存在,那么类型都是固定的,我们可以再申请个map
字符串替换,用正则添加双引号:
public void testJson(){
Mapmap = new HashMap ();
map.put("aaa", 111);
String json = JSON.toJSONString(map);
String json1 = json.replaceAll(":", ":\"");
json1 = json1.replaceAll("}", "\"}");
System.out.println(json);
System.out.println(json1);
}
public static String map2Json(Map map) {
if (map == null) {
return "{}";
} else {
Set keys = map.keySet();
StringBuffer jsonBuffer = new StringBuffer();
jsonBuffer.append("{");
Iterator it = keys.iterator();
while (true) {
while (it.hasNext()) {
Object key = it.next();
Object value = map.get(key);
if (value instanceof List) {
List jsonMap2 = (List) value;
jsonBuffer.append("\"" + key + "\":[");
Iterator iterator = jsonMap2.iterator();
while (iterator.hasNext()) {
Map jsonMap1 = (Map) iterator.next();
jsonBuffer.append(map2Json(jsonMap1));
if (iterator.hasNext()) {
jsonBuffer.append(",");
}
}
jsonBuffer.append("]");
if (it.hasNext()) {
jsonBuffer.append(",");
}
} else if (value instanceof Map) {
jsonBuffer.append("\"" + key + "\":");
Map jsonMap = (Map) value;
jsonBuffer.append(map2Json(jsonMap));
if (it.hasNext()) {
jsonBuffer.append(",");
}
} else {
jsonBuffer.append("\"" + key + "\":\""
+ (null != value && !"null".equals(value) ? string2Json(String.valueOf(value)) : "")
+ "\"");
if (it.hasNext()) {
jsonBuffer.append(",");
}
}
}
jsonBuffer.append("}");
return jsonBuffer.toString();
}
}
}