简体   繁体   中英

Converting Java generic object to XML using JAXB

I want to XML payloads like:

<ResponseDto>
    <ResponseHeader>
        <success>true</success>
    </ResponseHeader>
    <ResponseBody>
        <ObjectA>
        </ObjectA>
    </ResponseBody>
</ResponseDto>

and another payload like:

<ResponseDto>
    <ResponseHeader>
        <success>true</success>
    </ResponseHeader>
    <ResponseBody>
        <ObjectB>
        </ObjectB>
    </ResponseBody>
</ResponseDto>

so I want to make a class for ResponseDto which contains ResponseHeader Object and a generic Java Object in which I can place different types of objects, so I tried multiple types of Objects in a single class with @XMLElement(name = "ResponseBody") but it did not allow me to have same names of XMLElements

What can I do in this scenario? Thanks in advance.

Most of enterprise applications use JAXB. You could get many tutorials some are below.

  1. http://www.mkyong.com/java/jaxb-hello-world-example/
  2. https://examples.javacodegeeks.com/core-java/xml/bind/jaxb-marshal-example/
  3. https://www.javacodegeeks.com/2014/12/jaxb-tutorial-xml-binding.html

Step 1: First you would require to make xsd file. There are many online sites where xsd can be generated. Use http://xmlgrid.net/xml2xsd.html for now. XSD should look like this.

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="ResponseDto">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="ResponseHeader">
          <xs:complexType>
            <xs:sequence>
              <xs:element type="xs:string" name="success"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:element name="ResponseBody">
          <xs:complexType>
            <xs:sequence>
              <xs:element type="xs:string" name="ObjectA" minOccurs="0"/>
              <xs:element type="xs:string" name="ObjectB" minOccurs="0"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Refer my below post for reference. read and get xml values in java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM