Vineet Manohar is CTO / Co-Founder of online Car Search Engine, iSeeCars.com. Vineet is a DZone MVB and is not an employee of DZone and has posted 20 posts at DZone. You can read more from them at their website. View Full User Profile

Two Ways to Convert Java Map to String

05.08.2010
| 27116 views |
  • submit to reddit

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∅=  
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>

 

<?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.

 

 

From http://www.vineetmanohar.com/2010/05/07/2-ways-to-convert-java-map-to-string

Published at DZone with permission of Vineet Manohar, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Thomas Mueller replied on Sat, 2010/05/08 - 6:37am

What about using the Java source code format?

Stefan Kendall replied on Sun, 2010/05/09 - 6:02pm

Wouldn't something like GSON be a whole lot easier to use for serialization to a string?  

GSON gson = new GSON();
String json = gson.toJson(myObject);

Roger Lindsjö replied on Sun, 2010/09/05 - 3:52pm

Wouldn't it be quite easy for the first approach to be able to encode all strings by escaping &, = etc? Then you would also be able to escape null values. It would of course still only work for strings.

Michael Eric replied on Wed, 2012/09/26 - 3:53pm

In sample with XMLEncoder (line 08) instead of flush() method use close().
It make flush automatically and closes xml string correctly (closes tag).

redhat 

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.