Friday, April 16, 2010

Spring PropertyEditor for JSON map and array properties

I'm a big fan of Spring but found that it does not support map and list expressions in a property file to be substituted when using a PropertyPlaceholder. So I rolled my own PropertyEditor and can now express a map using JSON in my properties file e.g.:

myMapProperty ={"en-AU": "SKY", "ms": "SKY"}

Here's the property editor (depends on json-lib):

package <packagename>;

import java.beans.PropertyEditorSupport; 

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;

* Converts JSON expressions to Java arrays or maps and vice versa.
* @author huntc
public class JSONPropertyEditor extends PropertyEditorSupport {

public String getAsText() {
Object object = getValue();
JSON jsonObject = JSONSerializer.toJSON(object);
return jsonObject.toString();

public void setAsText(String text) {
JSON json = JSONSerializer.toJSON(text);

and here's what you must declare in your spring configuration xml:

<bean id="customEditorConfigurer"
<property name="customEditors">
<entry key="java.util.Map">
<bean class="<packagename>.JSONPropertyEditor" />

The above indicates that for any required substitution of a map, use my property editor e.g.:

<bean id="someBeanWithAMapProperty"
<property name="someMapProperty"
value="${myMapProperty}" />


No comments: