XML > JAXB > Serialize Complex Map to XML
Serialize Complex Map to XML
The following example shows serializing a POJO with complex map to an XML.
The POJO should have a no-arg default constructor and
@XmlRootElement annotation at class level.
package com.bethecoder.tutorials.jaxb.common;
import java.util.Map;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class MapData {
private Map<?, ?> data;
public Map<?, ?> getData () {
return data;
}
public void setData ( Map<?, ?> data ) {
this .data = data;
}
}
package com.bethecoder.tutorials.jaxb.tests;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import com.bethecoder.tutorials.jaxb.common.MapData;
public class ComplexMapToXML {
public static void main ( String [] args ) throws JAXBException {
Map<CountryKey, CountryValue> countryMap = new HashMap<CountryKey, CountryValue> () ;
countryMap.put ( new CountryKey ( 1 , "IN" ) , new CountryValue ( "India" )) ;
countryMap.put ( new CountryKey ( 2 , "US" ) , new CountryValue ( "America" )) ;
countryMap.put ( new CountryKey ( 3 , "UK" ) , new CountryValue ( "United Kingdom" )) ;
MapData mapData = new MapData () ;
mapData.setData ( countryMap ) ;
/**
* Create JAXB Context from the classes to be serialized
*/
JAXBContext context = JAXBContext.newInstance (
MapData.class, CountryKey.class, CountryValue. class ) ;
Marshaller m = context.createMarshaller () ;
m.setProperty ( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE ) ;
m.marshal ( mapData, System.out ) ;
}
}
class CountryKey {
private int countryId;
private String countryCode;
public CountryKey () {}
public CountryKey ( int countryId, String countryCode ) {
super () ;
this .countryId = countryId;
this .countryCode = countryCode;
}
public int getCountryId () {
return countryId;
}
public void setCountryId ( int countryId ) {
this .countryId = countryId;
}
public String getCountryCode () {
return countryCode;
}
public void setCountryCode ( String countryCode ) {
this .countryCode = countryCode;
}
}
class CountryValue {
private String value;
private String desc;
public CountryValue () {}
public CountryValue ( String value ) {
super () ;
this .value = value;
this .desc = value;
}
public String getValue () {
return value;
}
public void setValue ( String value ) {
this .value = value;
}
public String getDesc () {
return desc;
}
public void setDesc ( String desc ) {
this .desc = desc;
}
}
It gives the following output,