2 ways to convert Java Map to String

This article shows 2 ways to convert Java Map to String.

  • Approach 1: simple, lightweight – produces query string like output, but restrictive.
  • Approach 2: uses Java XML bean serialization, more robust but produces overly verbose output.

Approach 1: Map to query string format

Approach 1 converts a map to a query-string like output. Here’s what an output looks like:

name1=value1&name2=value2

Full code:

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class MapUtil {
 public static String mapToString(Map<String, String> map) {
   StringBuilder stringBuilder = new StringBuilder();

   for (String key : map.keySet()) {
    if (stringBuilder.length() > 0) {
     stringBuilder.append("&");
    }
    String value = map.get(key);
    try {
     stringBuilder.append((key != null ? URLEncoder.encode(key, "UTF-8") : ""));
     stringBuilder.append("=");
     stringBuilder.append(value != null ? URLEncoder.encode(value, "UTF-8") : "");
    } catch (UnsupportedEncodingException e) {
     throw new RuntimeException("This method requires UTF-8 encoding support", e);
    }
   }

   return stringBuilder.toString();
  }

  public static Map<String, String> stringToMap(String input) {
   Map<String, String> map = new HashMap<String, String>();

   String[] nameValuePairs = input.split("&");
   for (String nameValuePair : nameValuePairs) {
    String[] nameValue = nameValuePair.split("=");
    try {
     map.put(URLDecoder.decode(nameValue[0], "UTF-8"), nameValue.length > 1 ? URLDecoder.decode(
     nameValue[1], "UTF-8") : "");
    } catch (UnsupportedEncodingException e) {
     throw new RuntimeException("This method requires UTF-8 encoding support", e);
    }
   }

   return map;
  }
}

Example usage code

 Map<String, String> map = new HashMap<String, String>();
 map.put("color", "red");
 map.put("symbols", "{,=&*?}");
 map.put("empty", "");
 String output = MapUtil.mapToString(map);
 Map<String, String> parsedMap = MapUtil.stringToMap(output);
 for (String key : map.keySet()) {
  Assert.assertEquals(parsedMap.get(key), map.get(key));
 }

Output with Approach 1

symbols=%7B%2C%3D%26*%3F%7D&color=red&empty=

Caveat

  • Only supports String keys and values.
  • Due to the nature of serialization, null keys and values are not supported. Null will be converted to an empty String. This is because there is no way to distinguish between a null and an empty String in the serialized form. If you need support for null keys and values, use java.beans.XMLEncoder as shown below.

Approach 2: Java Bean XMLEncoder: Map to String

Java provides XMLEncoder and XMLDecoder classes as part of the java.beans package as a standard way to serialize and deserialize objects. This

 Map<String, String> map = new HashMap<String, String>();
 map.put("color", "red");
 map.put("symbols", "{,=&*?}");
 map.put("empty", "");
 ByteArrayOutputStream bos = new ByteArrayOutputStream();
 XMLEncoder xmlEncoder = new XMLEncoder(bos);
 xmlEncoder.writeObject(map);
 xmlEncoder.flush();

 String serializedMap = bos.toString()
 System.output.println(serializedMap);

Output with Approach 2

The serialized value is shown below. As you can see this is more verbose, but can accommodate different data types and null keys and values.

<?xml version="1.0" encoding="UTF-8"?>
<java version="1.5.0_17">
 <object>
  <void method="put">
   <string>symbols</string>
   <string>{,=&amp;*?}</string>
  </void>
  <void method="put">
   <string>color</string>
   <string>red</string>
  </void>
  <void method="put">
   <string>empty</string>
   <string></string>
  </void>
 </object>

Java Bean XMLDecoder: String to Map

 XMLDecoder xmlDecoder = new XMLDecoder(new ByteArrayInputStream(serializedMap.getBytes()));
 Map<String, String> parsedMap = (Map<String, String>) xmlDecoder.readObject();

 for (String key : map.keySet()) {
  Assert.assertEquals(parsedMap.get(key), map.get(key));
 }

Summary

While Java provides a standard (and overly verbose) way to serialize and deserialize objects, this articles discusses an alternative lightweight way to convert a Java Map to String and back. If you are serializing a map with non-null String keys and values, then you should be able to use this alternative way, otherwise use the Java bean serialization.

Related posts:

  1. 3 ways to serialize Java Enums
  2. New Java 7 Feature: String in Switch support
  3. 3 ways to run Java main from Maven
  4. Java Barcode API
  5. How to copy bean properties with a single line of code

2 comments to 2 ways to convert Java Map to String

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Get Adobe Flash playerPlugin by wpburn.com wordpress themes