String轉換到Map結構
下面的僅限于個人測試
最近工作中遇到一個問題,就是需要將一個Map < String, Object > 這樣的一個類型進行保存,后續并進行讀取的功能。當時沒有想起來用常見的序列化方式,想起來Map.toString()這樣可以將Map轉換到String,但是卻沒有對應的反向的方法。
自己就想著實現這樣一個功能,覺得不錯,故將轉換代碼貼在如下,但是map的序列化方式還有其他的很多方式,這個只是自己實現的map.toString()的反向轉換:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
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 ; 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; } |
測試用例
從簡單到復雜
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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<String, Object> mapresutl1 = (Map<String, Object>) getValue(str1); Map<String, Object> mapresutl2 = (Map<String, Object>) getValue(str2); Map<String, Object> mapresutl3 = (Map<String, Object>) getValue(str3); Map<String, Object> mapresutl4 = (Map<String, Object>) 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
1
|
String a = "{se=2016, format=xml, at=en co=3}" ; |
1
2
3
4
5
6
7
|
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(), "=" ); } |
1
2
|
System.out.println(docType); System.out.println( "a:" +docType.get( "a" )); |
不需要吧JSONArray或者JSONObject作為處理的轉存中介,String直接轉Map
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/zhouzhenyong/article/details/54224010