bert123
bert123

Reputation: 35

How to help JAXB unmarshaller choose correctly between two similar classes

I have two similar xml-annotated classes, in fact one is the same as the other with only a couple of added fields.

When trying to unmarshal XML representing the one of these objects, I'd like the unmarshaller to try first the one with fewer fields, and if that is not adequate, then use the expanded one to instantiate the object from the Xml. However I find that any XML that comes in that represents the 'smaller' class then gets instantiated as the 'bigger' class in all cases - even if the 'smaller' one would have been the correct one in that case. This then causes class cast problems down the line. The 'smaller' version never gets used. How can I get around this problem?

Apologies for the lack of concrete code examples, I hope I have been clear.

Upvotes: 0

Views: 92

Answers (1)

TamasGyorfi
TamasGyorfi

Reputation: 667

Maybe you could use namespaces for the XMLs and add the correct namespace info to your annotations.

Once I had the same problem, but we could not use namespaces. I did not find any solution back then, so we did a pattern match on the XML, and had different Jaxb contexts for the two classes.

(Btw, in our case the first class on the context's list got picked by the marshaller/unmarshaller).

Upvotes: 1

Related Questions