java中经常用到map.toSring() 直接转字符串网络传输或转储,取回后转回到Map对象,网上普遍做法是用JSON转,碰到MAP对象的KEY或VALUE值中有特殊字符串时就容易出问题,使用JSON转同样直接报错,无奈自己写,从网上看到大部分贴子是使用String.split()居多,但如果碰到MAP对象中的KEY和VALUE有"="或","时,用转义"\"时还是容易报错,无奈使用包裹符或自定义转义符,其中包裹符比较简单如"[]"或"{}",考虑到通用性,在转对象时,尽量少使用split(尽管效率高,但易出错,并且难查)。最后选择使用String.indexof()匹配,相对灵活,并且更易控制,直接上代码,我这边是使用LinkSetMap保证顺序性,所以加入了正反向输出
private static List<String> splitElement(String string,String splitStr){
List<String> strings=new ArrayList<>();
String prevStr=string;
int index=prevStr.indexOf(splitStr);
if(index>0) {
while ((index + splitStr.length()) < prevStr.length()) {
index = prevStr.indexOf(splitStr);
strings.add(prevStr.substring(0, index));
prevStr = prevStr.substring(index + splitStr.length());
}
}
strings.add(prevStr);
return strings;
}
public static LinkedHashMap<String,String> mapStringToMap(String str, String encloseStr,boolean isReverse) {
String sEncloseStr = "{";
String eEncloseStr = "}";
String splitElementStr = "";
String splitKeyValueStr = "";
switch (encloseStr.length()) {
case 2: {
sEncloseStr = sEncloseStr + encloseStr.charAt(0);
eEncloseStr = encloseStr.charAt(1) + eEncloseStr;
splitElementStr = encloseStr.charAt(1) + ", " + encloseStr.charAt(0);
splitKeyValueStr = encloseStr.charAt(1) + "=" + encloseStr.charAt(0);
break;
}
case 1: {
sEncloseStr = sEncloseStr + encloseStr;
eEncloseStr = encloseStr + eEncloseStr;
splitElementStr = encloseStr + ", " + encloseStr;
splitKeyValueStr = encloseStr + "=" + encloseStr;
}
default:
break;
}
if (str != null && str.contains(sEncloseStr) && str.contains(eEncloseStr)) {
str = str.substring(2, str.length() - 2);
if (str.length() < 2) {
return null;
}
} else {
return null;
}
str = str.trim();
List<String> strList = splitElement(str, splitElementStr);
if (strList.size() >0) {
LinkedHashMap<String, String> map = new LinkedHashMap<>();
if (!isReverse) {
for (String string : strList) {
int keyValueIndex = string.indexOf(splitKeyValueStr);
if (keyValueIndex >= 0 && (keyValueIndex + splitKeyValueStr.length()) < string.length()) {
String key = string.substring(0, string.indexOf(splitKeyValueStr));
String value = string.substring(string.indexOf(splitKeyValueStr) + splitKeyValueStr.length());
if (!key.isEmpty()) {
key = key.trim();
if (!key.isEmpty()) {
value = value.trim();
}
if (key.length() > 0) {
map.put(key, value);
}
}
}
}
} else {
for (int i = strList.size() - 1; i >= 0; i--) {
String string = strList.get(i);
if (string != null) {
int keyValueIndex = string.indexOf(splitKeyValueStr);
if (keyValueIndex >= 0 && (keyValueIndex + splitKeyValueStr.length()) < string.length()) {
String key = string.substring(0, string.indexOf(splitKeyValueStr));
String value = string.substring(string.indexOf(splitKeyValueStr) + splitKeyValueStr.length());
if (!key.isEmpty()) {
key = key.trim();
if (!key.isEmpty()) {
value = value.trim();
}
if (key.length() > 0) {
map.put(key, value);
}
}
}
}
}
}
return map;
}
return null;
}