Team lead for the TopLink/EclipseLink JAXB & SDO implementations, and the Oracle representative on those specifications. Blaise is a DZone MVB and is not an employee of DZone and has posted 44 posts at DZone. You can read more from them at their website. View Full User Profile

JAXB and java.util.Map

03.14.2013
| 14371 views |
  • submit to reddit

Is it ironic that it can be difficult to map the java.util.Map class in JAXB (JSR-222)?  In this post I will cover some items that will make it much easier.

Java Model Below is the Java model that we will use for this example.
Customer The Customer class has a property of type Map.  I chose this Map specifically since the key is a domain object and the value is a domain object.
package blog.map;
 
import java.util.*;
import javax.xml.bind.annotation.*;
 
@XmlRootElement
public class Customer {
 
    private Map<String, Address> addressMap = new HashMap<String, Address>();
 
    public Map<String, Address> getAddressMap() {
        return addressMap;
    }
 
    public void setAddressMap(Map<String, Address> addressMap) {
        this.addressMap = addressMap;
    }
 
}

Address
The Address class is just a typical POJO.
package blog.map;
 
public class Address {
 
    private String street;
 
    public String getStreet() {
        return street;
    }
 
    public void setStreet(String street) {
        this.street = street;
    }
 
}

Demo Code 
In the demo code below we will create an instance of Customer and populate its Map property.  Then we will marshal it to XML.
package blog.map;
 
import javax.xml.bind.*;
 
public class Demo {
 
    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Customer.class);
         
        Address billingAddress = new Address();
        billingAddress.setStreet("1 A Street");
         
        Address shippingAddress = new Address();
        shippingAddress.setStreet("2 B Road");
         
        Customer customer = new Customer();
        customer.getAddressMap().put("billing", billingAddress);
        customer.getAddressMap().put("shipping", shippingAddress);
         
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(customer, System.out);
    }
 
}

Use Case #1 - Default Representation
Below is a sample of XML corresponding to our domain model.  We see that each item in the Map has key and value elements wrapped in an entry element.
<?xml version="1.0" encoding="UTF-8"?>
<customer>
    <addressMap>
        <entry>
            <key>shipping</key>
            <value>
                <street>2 B Road</street>
            </value>
        </entry>
        <entry>
            <key>billing</key>
            <value>
                <street>1 A Street</street>
            </value>
        </entry>
    </addressMap>
</customer>

Use Case #2 - Rename the Element 
The JAXB reference implementation uses the @XmlElementWrapper annotation to rename the element corresponding to a Map property (we've added this support to MOXy in EclipseLink 2.4.2 and 2.5.0).  In previous versions of MOXy the @XmlElement annotation should be used.

Customer

We will use the @XmlElementWrapper annotation to rename the element corresponding to the addressMap property to be addresses.
package blog.map;
 
import java.util.*;
import javax.xml.bind.annotation.*;
 
@XmlRootElement
public class Customer {
 
    private Map<String, Address> addressMap = new HashMap<String, Address>();
 
    @XmlElementWrapper(name="addresses")
    public Map<String, Address> getAddressMap() {
        return addressMap;
    }
 
    public void setAddressMap(Map<String, Address> addressMap) {
        this.addressMap = addressMap;
    }
 
}

Output
Now we see that the addressMap element has been renamed to addresses.
<?xml version="1.0" encoding="UTF-8"?>
<customer>
    <addresses>
        <entry>
            <key>shipping</key>
            <value>
                <street>2 B Road</street>
            </value>
        </entry>
        <entry>
            <key>billing</key>
            <value>
                <street>1 A Street</street>
            </value>
        </entry>
    </addresses>
</customer>
Use Case #3 - Add Namespace Qualification

In this use case we will examine the impact of applying namespace qualification to a class that has a property of type java.util.Map. There was a MOXy bug related to the namespace qualification of Map properties that has been fixed in EclipseLink 2.4.2 and 2.5.0 (see:  http://bugs.eclipse.org/399297).

package-info
We will use the package level @XmlSchema annotation to specify that all fields/properties belonging to classes in this package should be qualified with the http://www.example.com namespace (see:  JAXB & Namespaces).
	
@XmlSchema(
    namespace="http://www.example.com",
    elementFormDefault=XmlNsForm.QUALIFIED)
package blog.map;
 
import javax.xml.bind.annotation.*;
Output 
We see that the elements corresponding to the Customer and Address classes are namespace qualified, but the elements corresponding to the Map class are not.  This is because the Map class is from the java.util package and therefore the information we specified on the package level @XmlSchema annotation does not apply.
<?xml version="1.0" encoding="UTF-8"?>
<ns2:customer xmlns:ns2="http://www.example.com">
    <ns2:addresses>
        <entry>
            <key>shipping</key>
            <value>
                <ns2:street>2 B Road</ns2:street>
            </value>
        </entry>
        <entry>
            <key>billing</key>
            <value>
                <ns2:street>1 A Street</ns2:street>
            </value>
        </entry>
    </ns2:addresses>
</ns2:customer>

Use Case #4 - Fix Namespace Qualification with an XmlAdapter  We can use an XmlAdapter to adjust the namespace qualification from the previous use case.

XmlAdapter (MapAdapter)
The XmlAdapter mechanism allows you to convert a class to another for the purpose of affecting the mapping (see:  XmlAdapter - JAXB's Secret Weapon).  To get the appropriate namespace qualification we will use an XmlAdapter to convert the Map to objects in the package for our domain model.
package blog.map;
 
import java.util.*;
import javax.xml.bind.annotation.adapters.XmlAdapter;
 
public class MapAdapter extends XmlAdapter<MapAdapter.AdaptedMap, Map<String, Address>> {
     
    public static class AdaptedMap {
         
        public List<Entry> entry = new ArrayList<Entry>();
  
    }
     
    public static class Entry {
         
        public String key;
         
        public Address value;
   
    }
 
    @Override
    public Map<String, Address> unmarshal(AdaptedMap adaptedMap) throws Exception {
        Map<String, Address> map = new HashMap<String, Address>();
        for(Entry entry : adaptedMap.entry) {
            map.put(entry.key, entry.value);
        }
        return map;
    }
 
    @Override
    public AdaptedMap marshal(Map<String, Address> map) throws Exception {
        AdaptedMap adaptedMap = new AdaptedMap();
        for(Map.Entry<String, Address> mapEntry : map.entrySet()) {
            Entry entry = new Entry();
            entry.key = mapEntry.getKey();
            entry.value = mapEntry.getValue();
            adaptedMap.entry.add(entry);
        }
        return adaptedMap;
    }
 
}

Customer
The @XmlJavaTypeAdapter annotation is used to specify the XmlAdapter on the Map property.  Note with an XmlAdaper applied we need to change the @XmlElementWrapper annotation to @XmlElement (evidence that @XmlElement should be used to annotate the element for a Map property).
package blog.map;
 
import java.util.*;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
 
@XmlRootElement
public class Customer {
 
    private Map<String, Address> addressMap = new HashMap<String, Address>();
 
    @XmlJavaTypeAdapter(MapAdapter.class)
    @XmlElement(name="addresses")
    public Map<String, Address> getAddressMap() {
        return addressMap;
    }
 
    public void setAddressMap(Map<String, Address> addressMap) {
        this.addressMap = addressMap;
    }
 
}

Output 
Now all the elements in the XML output are qualfied with the http://www.example.com namespace.
<?xml version="1.0" encoding="UTF-8"?>
<customer xmlns="http://www.example.com">
    <addresses>
        <entry>
            <key>shipping</key>
            <value>
                <street>2 B Road</street>
            </value>
        </entry>
        <entry>
            <key>billing</key>
            <value>
                <street>1 A Street</street>
            </value>
        </entry>
    </addresses>
</customer>

 

Published at DZone with permission of Blaise Doughan, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Lund Wolfe replied on Sun, 2013/03/17 - 2:39am

I assume you still need the XmlAdapter to unmarshal the xml back into a Map ?

Blaise Doughan replied on Sun, 2013/03/17 - 5:14am in response to: Lund Wolfe

In this post an XmlAdapter is only required to unmarshal the document from use case #4.  If a JAXB (JSR-222) impl can produce XML without an XmlAdapter then it can consume that XML without an XmlAdapter.

Lund Wolfe replied on Thu, 2013/03/21 - 10:37am

Thanks.  I guess we've had that ability since JAXB 2.0 and the first Java 6.

Jakub Stransky replied on Fri, 2013/11/15 - 11:01am

Is it possible to get it generated through xjc with schema?

I took this example, generated schema and from schema I tried to generate annotated classes back. What I got back was implementation with Lists and couple of NestedClasses. Is it possible to make it work somehow? I guess that I have to specify custom binding with supplied adapter however I wasn't able to get it right.

Does anybody give a try that?

Thanks

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.