DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Process Mining Key Elements
  • AI’s Role in Everyday Development
  • Migrating from React Router v5 to v6: A Comprehensive Guide
  • Playwright: Filter Visible Elements With locator.filter({ visible: true })

Trending

  • Building Custom Tools With Model Context Protocol
  • Build Your First AI Model in Python: A Beginner's Guide (1 of 3)
  • Cloud Cost Optimization for ML Workloads With NVIDIA DCGM
  • Navigating the LLM Landscape: A Comparative Analysis of Leading Large Language Models

JAXB and java.util.Map

By 
Blaise Doughan user avatar
Blaise Doughan
·
Mar. 14, 13 · Interview
Likes (0)
Comment
Save
Tweet
Share
59.2K Views

Join the DZone community and get the full member experience.

Join For Free

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>

 

Use case Element

Published at DZone with permission of Blaise Doughan, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Process Mining Key Elements
  • AI’s Role in Everyday Development
  • Migrating from React Router v5 to v6: A Comprehensive Guide
  • Playwright: Filter Visible Elements With locator.filter({ visible: true })

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: