Enterprise Java

JAXB and java.util.Map

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>

 

Reference: JAXB and java.util.Map from our JCG partner Blaise Doughan at the Java XML & JSON Binding blog.

Blaise Doughan

Team lead for the TopLink/EclipseLink JAXB & SDO implementations, and the Oracle representative on those specifications.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button