eclipse-ee4j / jaxb-ri

Jaxb RI
https://eclipse-ee4j.github.io/jaxb-ri/
BSD 3-Clause "New" or "Revised" License
202 stars 110 forks source link

XSD to JAVA generation. One-level XSD elements are transformed to List<Object> #1167

Open Tomas-Kraus opened 6 years ago

Tomas-Kraus commented 6 years ago

I seemed stuck with the generation of Java classes by XSD. When we have a few XSD elements placed on the same level which to be converted to Java Object, the JAXB generates a List<Object>. This issue violates the POJO > XML unmarshaling.

I have an XML message, it looks like:

<x:xmlMessage version="0.1">
    <animals>
        <dog>...</dog>
        <dog>...</dog>
        <cat>...</cat>
        <anotherAnimal>...</anotherAnimal>
    </animals>
</x:xmlMessage>

Here is an XSD schema to generate Java classes:

<xs:complexType name="animals">
    <xs:sequence minOccurs="0" maxOccurs="unbounded">
        <xs:choice>
            <xs:element name="dog" type="Dog" minOccurs="0" maxOccurs="1"/>
            <xs:element name="Cat" type="Cat" minOccurs="0" maxOccurs="1"/>
            <xs:element name="anotherAnimal" type="AnotherAnimal" minOccurs="0" maxOccurs="1"/>
        </xs:choice>
    </xs:sequence>
</xs:complexType>

<xs:complexType name="Dog">
<xs:sequence>
    ...
</xs:sequence>
</xs:complexType>

<xs:complexType name="Cat">
<xs:sequence>
    ...
</xs:sequence>
</xs:complexType>

<xs:complexType name="AnotherAnimal">
<xs:sequence>
    ...
</xs:sequence>
</xs:complexType> 

The generated class looks like:

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "Animals", propOrder = {
        "dogOrCatOrAnotherAnimal"
    })
    public class Animals implements Equals2, ToString2
    {

    @XmlElements({
        @XmlElement(name = "dog", type = Dog.class),
        @XmlElement(name = "cat", type = Cat.class),
        @XmlElement(name = "anotherAnimal", type = AnotherAnimal.class)
    })
    protected List<Object> dogOrCatOrAnotherAnimal;
    ...

    }

So, each list of <animals> can contain an unbounded list of dogs, cats, and other animals.

So, my problem is in this List<Object> dogOrCatOrAnotherAnimal. Because it has List of Objects instead of Map of typed classes.

But the main problem is, this class uses for XML <> JSON conversions and I am able to marshal such object to JSON easily, but cannot unmarshal back to the XML string due to the wrong List structure.

I need either a Map of typed objects or any possible solution how to solve this problem. And one more problem, is here any changes entirely into the XSD schema are forbidden.

What could be the best way to fix this problem?

Tomas-Kraus commented 5 years ago