Showing posts with label property editor. Show all posts
Showing posts with label property editor. Show all posts

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 {

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

@Override
public void setAsText(String text) {
JSON json = JSONSerializer.toJSON(text);
setValue(json);
}
}

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

<bean id="customEditorConfigurer"
class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Map">
<bean class="<packagename>.JSONPropertyEditor" />
</entry>
</map>
</property>
</bean>

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

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