JAVA/Android Map and String Conversion Method, androidmap
In Android development, Map and String conversion are often used in some requirements. Using net. sf. json. JSONObject. fromObject can easily convert string to Map. However, you need to import the jar package. In (android), resources are easily wasted. The following method can meet the requirements when the jar package cannot be imported.
1) convert the Map to a string such as username 'chenziwen ^ password' 1234.
/*** Method Name: transMapToString * input parameter: map * return value: String, for example, username 'chenziwen ^ password' 1234 */public static String transMapToString (Map map) {java. util. map. entry entry; StringBuffer sb = new StringBuffer (); for (Iterator iterator = map. entrySet (). iterator (); iterator. hasNext ();) {entry = (java. util. map. entry) iterator. next (); sb. append (entry. getKey (). toString ()). append ("'"). append (null = entry. getValu E ()? "": Entry. getValue (). toString (). append (iterator. hasNext ()? "^": "");} Return sb. toString ();}
2) convert the string like username 'chenziwen ^ password' 1234 to Map
/*** Method Name: transStringToMap * input parameter: mapString, for example, username 'chenziwen ^ password' 1234 * return value: Map */public static Map transStringToMap (String mapString) {Map map = new HashMap (); java. util. stringTokenizer items; for (StringTokenizer entrys = new StringTokenizer (mapString, "^"); entrys. hasMoreTokens (); map. put (items. nextToken (), items. hasMoreTokens ()? (Object) (items. nextToken (): null) items = new StringTokenizer (entrys. nextToken (), "'"); return map ;}