Two Ways to Convert Java Map to String
Join the DZone community and get the full member experience.
Join For FreeThis 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∅=
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>{,=&*?}</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.
From http://www.vineetmanohar.com/2010/05/07/2-ways-to-convert-java-map-to-string
Opinions expressed by DZone contributors are their own.
Comments