JAVA/Android Map and String Conversion Method, androidmap

Source: Internet
Author: User

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 ;}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.