views:

269

answers:

1

I need to serialise a javabean (with arbitrary nested beans) to plain text, and then later restore as an Object graph.

For the purposes of this question I am not interested in XML, JSON, etc. but rather name/value pairs.

The Spring DataBinder is great for turning a list of name/value pairs into a real Object. For example we can supply:

values.addPropertyValue("id", "6789");
values.addPropertyValue("nestedBean[0].systemId", "FOO");
values.addPropertyValue("nestedBean[1].systemId", "BAR");

And use the DataBinder to produce a top level bean (with property id) containing a List of two nested beans.

My question is, how can I easily serialise a bean into the format that DataBinder expects?

I would expect something of the form:

Map<String,String> reduceBeanToNameValuePairs(Object bean)

but have had no luck finding anything of the sort.

+1  A: 

You could have a look at Commons BeanUtils. Its BeanMap class provides an entrySet method for accessing the wrapped bean's properties as entries of a map.

This functionality is already sufficient for "flat" beans and would probably provide a good starting point for adding the necessary recursion for nested bean graphs.

springify