java string转map_Java中string转map工具类

String zhi="{companyid=99999, villageCode=999999999, companyName=在测试, companyAdress=在测试, companyPic=在测试, lon=99.99, lat=88.88, mrowTime=2019-09-09 22:15:09}";

Map mapone=stringToMap(zhi);public static MapstringToMap(String str) {

Map map = new HashMap();if (str.startsWith("{") && str.endsWith("}")) {

str= str.substring(1, str.length());

str= str.substring(0, str.length() - 1);

String[] eArr= str.split("=");

String key= "";for (int i = 0; i < eArr.length; i++) {

String tempStr=eArr[i];//如果为最后一个直接做为值进行封装

if (i == eArr.length - 1) {

map.put(key, tempStr.replace(" ", ""));

}else{//判断字符串中是否包含又"'{', '}','[',']'"字符

if ((tempStr).contains("{") || (tempStr).contains("[") || (tempStr).contains("}") || (tempStr).contains("]")) {

Stack stackChar = new Stack();

Integer stackLength= null;for (int j = 0; j < tempStr.length(); j++) {char c =tempStr.charAt(j);if ((c + "").equals("{") || (c + "").equals("[")) {

stackChar.push(c+ "");

stackLength=stackChar.size();

}else if ((c + "").equals("}") || (c + "").equals("]")) {

stackChar.pop();

stackLength=stackChar.size();

}else if ((c + "").equals(",")) {if (stackLength == 0) {//跳出该循环,并从该处进行分离

String jsonStr = tempStr.substring(0, j);

String newKey= tempStr.substring(j + 1, tempStr.length());

map.put(key, jsonStr.replace(" ", ""));

key= newKey.replace(" ", "");//清空栈

stackChar.clear();break;

}

}

}

}else{//判断是否有逗号

if (tempStr.contains(",")) {

Stack stack = new Stack();//从分离的字符串中获取上一个key的value和下一个key的name

for (int j = 0; j < tempStr.length(); j++) {char c =tempStr.charAt(j);if (!(c + "").equals(",")) {

stack.push(c+ "");

}else if ((c + "").equals(" ")) {continue;

}else{

String sStr=stack.pop();if (sStr.equals("\"")) {

stack.push(sStr);

stack.push(c+ "");

}else{

String jsonStr= tempStr.substring(0, j);

String newKey= tempStr.substring(j + 1, tempStr.length());

map.put(key, jsonStr.replace(" ", ""));

key= newKey.replace(" ", "");//清空栈

stack.clear();break;

}

}

}

}else{

key= tempStr.replace(" ", "");

}

}

}

}

}else{

System.out.println("不是正确的Map格式");

}returnmap;

}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部