JAXB XmlAdapter HashMap Example

Connect with

Oracle JavaHow to unmarshal and marshal JAXB XMLAdapter HashMap example in Java using @XmlJavaTypeAdapter, where key is a string and value is a java object.

1. Sample of XML with Map (key/value)

This is one type of challenges , how you can convert from XML to java object and java Object to XML using JAXB in java. This is straight forward , let us explain step by step.



     Ranjeet Jha    
     
        
            shippingAddress
            
                Banglore
                Street no 2
            
        
        
            billingAddress
            
                New Delhi
                B-672, DDA Flats, Bindapur, Dwarka
            
        
    
    


2. create java class for value of Map

File: Address.java

package com.mysoftkey.jaxb.map;
public class Address {
	private String street;
	private String city;
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getStreet() {
		return street;
	}
	public void setStreet(String street) {
		this.street = street;
	}
}

This java class for building xml elements as:

New Delhi
B-672, DDA Flats, Bindapur, Dwarka

3. For top level XML element and Java class

package com.mysoftkey.jaxb.map;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlRootElement
// @XmlType(namespace="http://www.mysoftkey.com/type")
public class Customer {
	private long id;
	private String name;

	// this is optional
	private Map addressMap = new HashMap();

	@XmlJavaTypeAdapter(MapAdapter.class)
	// @XmlElement(name="addresses")
	public Map getAddressMap() {
		return addressMap;
	}

	public void setAddressMap(Map addressMap) {
		this.addressMap = addressMap;
	}

	@XmlAttribute(name = "cust_id")
	public long getId() {
		return id;
	}

	// @XmlElement
	public String getName() {
		return name;
	}

	public void setId(long id) {
		this.id = id;
	}

	public void setName(String name) {
		this.name = name;
	}

}

For root level element and one element i.e. name and one attribute i.e. cust_id


--
 Ranjeet Jha

4. XMLAdaptor for Map etry (key/value)

package com.mysoftkey.jaxb.map;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class MapAdapter extends XmlAdapter entry = new ArrayList();
	}

	public static class Entry {
		public String key;
		public Address value;
	}

	@Override
	public Map<String, address> unmarshal(AdaptedMap adaptedMap) throws Exception {
		Map map = new HashMap();
		for (Entry entry : adaptedMap.entry) {
			map.put(entry.key, entry.value);
		}
		return map;
	}

	@Override
	public AdaptedMap marshal(Map map) throws Exception {
		AdaptedMap adaptedMap = new AdaptedMap();
		for (Map.Entry mapEntry : map.entrySet()) {
			Entry entry = new Entry();
			entry.key = mapEntry.getKey();
			entry.value = mapEntry.getValue();
			adaptedMap.entry.add(entry);
		}
		return adaptedMap;
	}
}

For marshaling and un-marshaling of Map>


    billingAddress
    
      New Delhi
      B-672, DDA Flats, Bindapur, Dwarka
    

5. JAXB XMLAdapter Example

– create java pojo and assign accordingly.
– write marshaling and unmarshling code

File:

package com.mysoftkey.jaxb.map;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.PropertyException;
import javax.xml.bind.Unmarshaller;

public class MapXMLAdaptorExample {
 // create a docs folder under the project parallet to src to goes output of the program.
 private static final String XML_PATH = "./docs/customerMap.xml";

 /**
  * @param args
  * @throws Exception
  */
 public static void main(String[] args) throws Exception {
  try {
   unmarshalCustomer();
  } catch (Exception e) {
   e.printStackTrace();
  }
}

 /**
  * to convert from xml to java object .
  * @throws JAXBException
  * @throws PropertyException
  */
 private static Customer unmarshalCustomer() throws JAXBException, PropertyException {
  JAXBContext jc = marshaCustomer();

  Unmarshaller unmarshaller = jc.createUnmarshaller();
  Customer unMarshCustomer = (Customer) unmarshaller.unmarshal(new File(XML_PATH));

  System.out.println(unMarshCustomer.getName());
  return unMarshCustomer;
 }

 /**
  * to convert from java object to XML .
  * @return
  * @throws JAXBException
  * @throws PropertyException
  */
 private static JAXBContext marshaCustomer() throws JAXBException, PropertyException {
  JAXBContext jc = JAXBContext.newInstance(Customer.class);

  Address billingAddress = new Address();
  billingAddress.setStreet("B-672, DDA Flats, Bindapur, Dwarka");
  billingAddress.setCity("New Delhi");

  Address shippingAddress = new Address();
  shippingAddress.setStreet("Street no 2");
  shippingAddress.setCity("Banglore");

  Customer customer = new Customer();
  customer.getAddressMap().put("billingAddress", billingAddress);
  customer.getAddressMap().put("shippingAddress", shippingAddress);
  customer.setId(123);
  customer.setName("Ranjeet Jha");

  Marshaller marshaller = jc.createMarshaller();
  marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

  // write to console
  marshaller.marshal(customer, System.out);

  // Write to File
  marshaller.marshal(customer, new File(XML_PATH));
  return jc;
 }

}

Output:



  
     
        shippingAddress
        
            Banglore
            Street no 2
        
    
    
        billingAddress
        
          New Delhi
          B-672, DDA Flats, Bindapur, Dwarka
        
     
  
  Ranjeet Jha

6. Reference

oracle.com
I hope you enjoyed this post about JAXB XMlAdapter HashMap example in java, visit Core Java tutorial for more blog post.

Your comment is welcome to improve this post. Happy Learning! 🙂


Connect with

Leave a Comment

Your email address will not be published. Required fields are marked *