使用String转换到Map结构

网友投稿 732 2022-11-26

使用String转换到Map结构

使用String转换到Map结构

目录String转换到Map结构下面的仅限于个人测试测试用例特殊格式的String转Map

String转换到Map结构

下面的仅限于个人测试

最近工作中遇到一个问题,就是需要将一个Map < String, Object > 这样的一个类型进行保存,后续并进行读取的功能。当时没有想起来用常见的序列化方式,想起来Map.toString()这样可以将Map转换到String,但是却没有对应的反向的方法

自己就想着实现这样一个功能,觉得不错,故将转换代码贴在如下,但是map的序列化方式还有其他的很多方式,这个只是自己实现的map.toString()的反向转换:

public Object getValue(String param) {

Map map = new HashMap();

String str = "";

String key = "";

Object value = "";

char[] charList = param.toCharArray();

boolean valueBegin = false;

for (int i = 0; i < charList.length; i++) {

char c = charList[i];

if (c == '{') {

if (valueBegin == true) {

value = getValue(param.substring(i, param.length()));

i = param.indexOf('}', i) + 1;

map.put(key, value);

}

} else if (c == '=') {

valueBegin = true;

MjXpIPqB key = str;

str = "";

} else if (c == ',') {

valueBegin = false;

value = str;

str = "";

map.put(key, value);

} else if (c == '}') {

if (str != "") {

value = str;

}

map.put(key, value);

return map;

} else if (c != ' ') {

str += c;

}

}

return map;

}

测试用例

从简单到复杂

public void testFun() {

String str1 = "{idCard=123, phonenum=1234}";

String str2 = "{idCard=123, phonenum=1234, map={hhaha=haha}}";

String str3 = "{idCard=123, phonenum=1234, map={hhaha=haha}, nn={en=ha}}";

String str4 = "{nn={en=ha}, idCard=123, phonenum=1234, map={hhaha=ni, danshi={ke=shi}}}";

Map mapresutl1 = (Map) getValue(str1);

Map mapresutl2 = (Map) getValue(str2);

Map mapresutl3 = (Map) getValue(str3);

Map mapresutl4 = (Map) getValue(str4);

System.out.println(mapresutl1.toString());

System.out.println(mapresutl2.toString());

System.out.println(mapresutl3.toString());

System.out.println(mapresutl4.toString());

}

输出结果:

{idCard=123, phonenum=1234} {idCard=123, phonenum=1234, map={hhaha=haha}} {nn={en=ha}, idCard=123, phonenum=1234, map={hhaha=haha}} {nn={en=ha}, idCard=123, phonenum=1234, map={hhaha=ni, danshi={ke=shi}}}

该函数的功能是能够处理将Map < String, Object > .toString的字符串再次翻转到对应的Map中,其中Object只能是Map类型或者其他基本的类型才行,如果是复杂的这里不涉及,或者说可以将复杂的结构用Map的键值对来表示,这样就可以用这种方式。

后来发现,序列化的方式有很多,所以也没有必要自己去实现一个,map也是可以进行序列化的

如下几个序列化方式

java自带的,json,hession

还有阿里的fastjson,protobuff等

上面几个都可以实现map的序列化

特殊格式的String转Map

String a ="{se=2016, format=xml, at=en co=3}";

a = a.substring(1, a.length()-1);

Map docType = new HashMap();

java.util.StringTokenizer items;

for(StringTokenizer entrys = new StringTokenizer(a, ", ");entrys.hasMoreTokens();

docType.put(items.nextToken(), items.hasMoreTokens() ? ((Object) (items.nextToken())) : null)){

items = new StringTokenizer(entrys.nextToken(), "=");

}

System.out.println(docType);

System.out.println("a:"+docType.get("a"));

不需要吧JSONArray或者JSONObject作为处理的转存中介,String直接转Map

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:python3教程:*和**的打包和解包的用法
下一篇:第九章 其他参考资料(二)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~