What is the quickest way to serialize a Java object to Map (and parse back) with minimum code writing?
I have a system that entities (from database, represented as Java objects through OR开发者_StackOverflow中文版M) will be read by XML-RPC clients, my existing way is to serialize them via a StructSerializer
, which in its code, we read properties out from the Java object, including calling another StructSerializer
to serialize/parse a property, e.g.
Surrogate parse(Map<String, Object> in) {
String name = in.get(Surrogate.NAME, String.class);
...
}
Map<String, Object> serialize(Surrogate in) {
out.put(Surrogate.ID, in.getId());
out.put(Surrogate.USER, userSerializer.serialize(in.getUser()))
}
What I am looking now is to eliminate/automate/minimize writing such code. Also, XML-RPC-compatible is not really the issue.
Thanks a lot.
Edited:
To elaborate further, XML conversion is handled by Apache XML-RPC, all I need is to dump in a Map for it to work on. What I need now is a unified/well-accepted way to convert Java objects to Map.
I refined my search and found: How to convert a Java object (bean) to key-value pairs (and vice versa)?
That suggests BeanUtils as a good solution.
If you don't need to be compatible, there are a number of options: XMLEncoder, XStream, Castor. They all require very little code to write, unless you need something fancy. XMLEncoder is included in the JRE, others are additional libraries.
I like XStream for this kind of work - http://x-stream.github.io/
All you have to do is annotate your classes and feed them into the XStream serializer/deserializer. You may want to annotate specific fields to tune the output, but you usually don't have to.
精彩评论