Tuesday, July 29, 2014

JAXB marshalling and unmarshalling of Hashtable

It is not possible to Marshall or Unmarshall a Hashtable directly however you can achieve it using a Holder class (wrapper class). With the help of Holder class you can get the default XML format as shown below -

Default XML format -
<mapHolder>
    <htmlColorCode>
        <entry>
            <key>blue</key>
            <value>0000FF</value>
        </entry>
        <entry>
            <key>green</key>
            <value>00FF00</value>
        </entry>
        <entry>
            <key>red</key>
            <value>FF0000</value>
        </entry>
    </htmlColorCode>
</mapHolder>

However if you need to customize the XML format like the one shown below you may need to use XmlAdapter.

<colorMap>
    <colors>
        <item code="0000FF" color="blue"/>
        <item code="00FF00" color="green"/>
        <item code="FF0000" color="red"/>
    </colors>
</colorMap>

Method 1 - Using Wrapper class

Output -
--Marshalling--
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<mapHolder>
    <htmlColorCode>
        <entry>
            <key>blue</key>
            <value>0000FF</value>
        </entry>
        <entry>
            <key>green</key>
            <value>00FF00</value>
        </entry>
        <entry>
            <key>red</key>
            <value>FF0000</value>
        </entry>
    </htmlColorCode>
</mapHolder>

--Unmarshalling--
{blue=0000FF, green=00FF00, red=FF0000}


Method 2 - Using Java XmlAdapter

Output - 
--Marshalling--
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<colorMap>
    <colors>
        <item code="0000FF" color="blue"/>
        <item code="00FF00" color="green"/>
        <item code="FF0000" color="red"/>
    </colors>
</colorMap>

--Unmarshalling--

{blue=0000FF, green=00FF00, red=FF0000}

No comments:

Post a Comment