views:

88

answers:

3

Every time I've searched for something on how to serialize to XML, I found the bean serializers. It seems that everything has to be declared as a property, which defeats my purpose. I want to serialize complex hierarchies (until they get to primitives, of course) in XML, start with (say) a Dictionary or List as the parent object.

What options are there for automatic XML serialization?

I found some references to JAXB from 2004, is that still the way to go?

+2  A: 

Try the XStream library. It will easily serialize any complex object hierarchy you can throw at it.

Kevin
interesting, that might do it. While I like built-in Java stuff, ease-of-use is the point.
Yar
+3  A: 

I've had a lot of success with JAXB, especially when using the support for it in NetBeans. I know for a fact it supports lists. I haven't tried it with maps, but I suspect it works. If nothing else, just make a simple bean that contains the list and let that be the serialized bean.

Jon
Yes to JAXB - it is still the way to go.
GreenieMeanie
Actually, rereading your question, are you saying that you don't know ahead of time what kind of structure your data will contain?
Jon
@Jon, yes, but I know the type of the class that holds all the other stuff.
Yar
If you can write an unambiguous Schema for your document type, JAXB should be able to handle it. It might get a little messy, but it should be able to handle it. For example, you might have to declare it as an element ContainerType that contains 0..n ContainerTypes, 0..n IntContainerTypes, 0..n StringContainerTypes, etc, depending on exactly what you're doing.
Jon
A: 

You can use the standard java.bean.XMLEncoder / Decoder classes to serialize collections because the mechanism allows for the calling of methods via XML. The output looks something like:

<object class="java.util.ArrayList">
  <void method="add">
    <string>Hello</string>
  </void>
  <void method="add">
    <string>World</string>
  </void>
</object>

Of course this has weaknesses; for example you cannot easily serialize a Collections.emptyXXXX() but there are workarounds. But because everything works according to the publicly-supported API of the classes, the persistent XML form is resilient to schema changes.

I've found it a very useful persistent mechanism for Java objects.

oxbow_lakes
Um hmmm... my last time around testing it, it didn't work. I'll try again and upvote you if it does.
Yar
Where's my upvote then? I know it works because I've written systems based around it :-)
oxbow_lakes