tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 XML > JAXB > Serialize Simple Map to XML

Serialize Simple Map to XML 

The following example shows serializing a POJO with simple map to an XML. The POJO should have a no-arg default constructor and @XmlRootElement annotation at class level.

File Name  :  
com/bethecoder/tutorials/jaxb/common/MapData.java 
   
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;
  }
  
}
   

File Name  :  
com/bethecoder/tutorials/jaxb/tests/SimpleMapToXML.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
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 SimpleMapToXML {

  public static void main (String [] argsthrows JAXBException {
    
    Map<String, String> countryMap = new HashMap<String, String>();
    countryMap.put("IN""India");
    countryMap.put("US""America");
    countryMap.put("UK""United Kingdom");
    
    MapData mapData = new MapData();
    mapData.setData(countryMap);
    
    /**
     * Create JAXB Context from the classes to be serialized
     */
    JAXBContext context = JAXBContext.newInstance(MapData.class);  
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);  
    m.marshal(mapData, System.out);  

  }
}
   

It gives the following output,
File Name  :  OUTPUT


                    Print

   



Books Recommendation

 
 
bl  br