Java 8 – JAXB: Unmarshalling generics and element with same name

I’m querying several endpoints of an API that returns XML data.
The XML returned by the various endpoints are very similar to each other, with the exception of the name of one element (simplified examples below).

User.xml

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <header>
        <userAPI info="User info"/>
    </header>
    <userAPI>
        <username>charles</username>
    </userAPI>
</root>

Order.xml

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <header>
        <orderAPI info="Order info"/>
    </header>
    <orderAPI>
        <orderId>1</orderId>
    </orderAPI>
</root>

I managed to implement classes using generics but I’m encountering a problem related to elements that have the same name, in fact, a peculiarity of these XMLs is that they always have 2 elements with the same name (one child of header and one child of root):

  • userAPI for the User.xml file
  • orderAPI for the Order.xml file

Below are the classes implemented (using Lombok) for unmarshaling the User.xml file

pom.xml

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.30</version>
    <scope>provided</scope>
</dependency>

UserApiHeader.java

@Data
@XmlRootElement(name = "userAPI")
@XmlAccessorType(XmlAccessType.FIELD)
public class UserApiHeader {
    @XmlAttribute
    private String info;
}

UserApi.java

@Data
@XmlRootElement(name = "userAPI")
@XmlAccessorType(XmlAccessType.FIELD)
public class UserApi {
    @XmlElement
    private String username;
}

Header.java

@Data
@XmlRootElement(name = "header")
@XmlAccessorType(XmlAccessType.FIELD)
public class Header<T> {
    @XmlAnyElement(lax = true)
    private T headerDetail;
}

Root.java

@Data
@XmlRootElement(name = "root")
@XmlAccessorType(XmlAccessType.FIELD)
public class Root<T, E> {
    @XmlElement
    private Header<T> header;
    @XmlAnyElement(lax = true)
    private E body;
}

Main.java

public class Main {
    public static void main(String[] args) {
        String xml = "<?xml version="1.0" encoding="UTF-8"?>rn"
                + "<root>rn"
                + "    <header>rn"
                + "        <userAPI info="User info"/>rn"
                + "    </header>rn"
                + "    <userAPI>rn"
                + "        <username>charles</username>rn"
                + "    </userAPI>rn"
                + "</root>";
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(Root.class, UserApi.class, UserApiHeader.class);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            @SuppressWarnings("unchecked")
            Root<UserApiHeader, UserApi> root = (Root<UserApiHeader, UserApi>) unmarshaller.unmarshal(new StringReader(xml));
            System.out.println("Header detail: " + root.getHeader().getHeaderDetail());
            System.out.println("Body:          " + root.getBody());
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}

Result

Header detail: UserApiHeader(info=User info)
Body:          UserApiHeader(info=null)

From the console result you can see that unmarshalling associates the UserApiHeader class with both userAPI elements, therefore it fails to deserialize the root.userAPI element returning null

Another thing I noticed is that if I reverse the orders of the classes when instantiating the JAXBContext, unmarshalling associates the UserApi class with both userAPI, therefore it fails to deserialize the root.header.userAPI element returning null

public class Main {
    public static void main(String[] args) {
        // ...
            JAXBContext jaxbContext = JAXBContext.newInstance(Root.class, UserApiHeader.class, UserApi.class);
        // ...
    }
}
Header detail: UserApi(username=null)
Body:          UserApi(username=charles)

The problem described does not arise if I change the name of one of the two elements (which, however, I cannot actually do since, as anticipated, they are files that I receive from an API).

Any suggestions?
Thanks in advance

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật