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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
Partner Zones AWS Cloud
by AWS Developer Relations
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
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Languages
  4. Mixing Nesting and References with JAXB's XmlAdapter

Mixing Nesting and References with JAXB's XmlAdapter

Blaise Doughan user avatar by
Blaise Doughan
·
Oct. 21, 11 · Interview
Like (0)
Save
Tweet
Share
11.20K Views

Join the DZone community and get the full member experience.

Join For Free

Recently I came across a question on Stack Overflow asking if JAXB could marshal the first occurrence of an object as containment and all subsequent occurrences as a reference.  Below is an expanded version of my answer (up votes appreciated) demonstrating how this can be achieved by leveraging JAXB's XmlAdapter.

input.xml

The following is the XML document I will use for this example. The 2nd "other-phone-number" element refers to the same data as the "primary-phone-number" element, and the 3rd "other-phone-number" element refers to the same data as the 1st "other-phone-number" element.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer>
    <primary-phone-number id="B">555-BBBB</primary-phone-number>
    <other-phone-number id="A">555-AAAA</other-phone-number>
    <other-phone-number reference="B"/>
    <other-phone-number reference="A"/>
</customer>

Customer

The Customer class maintains references to PhoneNumber objects. The same instance of PhoneNumber may be referenced multiple times.

package package blog.xmladapter.stateful;
 
import java.util.List;
import javax.xml.bind.annotation.*;
 
@XmlRootElement
@XmlType(propOrder={"primaryPhoneNumber", "otherPhoneNumbers"})
public class Customer {
 
    private PhoneNumber primaryPhoneNumber;
    private List<PhoneNumber> otherPhoneNumbers;
 
    @XmlElement(name="primary-phone-number")
    public PhoneNumber getPrimaryPhoneNumber() {
        return primaryPhoneNumber;
    }
 
    public void setPrimaryPhoneNumber(PhoneNumber primaryPhoneNumber) {
        this.primaryPhoneNumber = primaryPhoneNumber;
    }
 
    @XmlElement(name="other-phone-number")
    public List<PhoneNumber> getOtherPhoneNumbers() {
        return otherPhoneNumbers;
    }
 
    public void setOtherPhoneNumbers(List<PhoneNumber> phoneNumbers) {
        this.otherPhoneNumbers = phoneNumbers;
    }
 
}

PhoneNumber

This is a class that can either appear in the document itself or as a reference. This will be handled using an XmlAdapter. An XmlAdapter is configured using the @XmlJavaTypeAdapter annotation. Since we have specified this adapter at the type/class level it will apply to all properties referencing the PhoneNumber class:

package blog.xmladapter.stateful;
 
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
 
@XmlJavaTypeAdapter(PhoneNumberAdapter.class)
@XmlTransient
public class PhoneNumber {
 
    private String id;
    private String number;
 
    @XmlAttribute
    public String getId() {
        return id;
    }
 
    public void setId(String id) {
        this.id = id;
    }
 
    @XmlValue
    public String getNumber() {
        return number;
    }
 
    public void setNumber(String number) {
        this.number = number;
    }
 
    @Override
    public boolean equals(Object object) {
        if(null == object || object.getClass() != this.getClass()) {
            return false;
        }
        PhoneNumber test = (PhoneNumber) object;
        if(!equals(id, test.getId())) {
            return false;
        }
        return equals(number, test.getNumber());
    }
 
    private boolean equals(String control, String test) {
        if(null == control) {
            return null == test;
        } else {
            return control.equals(test);
        }
    }
 
    @Override
    public int hashCode() {
        return id.hashCode();
    }
 
}


PhoneNumberAdapter

Below is the implementation of the XmlAdapter. Note that we must maintain if the PhoneNumber object has been seen before. If it has we only populate the id portion of the AdaptedPhoneNumber object.

package blog.xmladapter.stateful;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.adapters.XmlAdapter;
 
public class PhoneNumberAdapter extends XmlAdapter<PhoneNumberAdapter.AdaptedPhoneNumber, PhoneNumber>{
 
    private List<PhoneNumber> phoneNumberList = new ArrayList<PhoneNumber>();
    private Map<String, PhoneNumber> phoneNumberMap = new HashMap<String, PhoneNumber>();
 
    public static class AdaptedPhoneNumber extends PhoneNumber {
        @XmlAttribute
        public String reference;
    }
 
    @Override
    public AdaptedPhoneNumber marshal(PhoneNumber phoneNumber) throws Exception {
        AdaptedPhoneNumber adaptedPhoneNumber = new AdaptedPhoneNumber();
        if(phoneNumberList.contains(phoneNumber)) {
            adaptedPhoneNumber.reference = phoneNumber.getId();
        } else {
            adaptedPhoneNumber.setId(phoneNumber.getId());
            adaptedPhoneNumber.setNumber(phoneNumber.getNumber());
            phoneNumberList.add(phoneNumber);
        }
        return adaptedPhoneNumber;
    }
 
    @Override
    public PhoneNumber unmarshal(AdaptedPhoneNumber adaptedPhoneNumber) throws Exception {
        PhoneNumber phoneNumber = phoneNumberMap.get(adaptedPhoneNumber.reference);
        if(null == phoneNumber) {
            phoneNumber = new PhoneNumber();
            phoneNumber.setId(adaptedPhoneNumber.getId());
            phoneNumber.setNumber(adaptedPhoneNumber.getNumber());
            phoneNumberMap.put(phoneNumber.getId(), phoneNumber);
        }
        return phoneNumber;
    }
 
}


Demo

To ensure the same instance of the XmlAdapter is used for the entire marshal and unmarshal operations we must specifically set an instance of the XmlAdapter on both the Marshaller and Unmarshaller:

package blog.xmladapter.stateful;
 
import java.io.File;
 
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
 
public class Demo {
 
    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Customer.class);
 
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        unmarshaller.setAdapter(new PhoneNumberAdapter());
        File xml = new File("src/blog/xmladapter/stateful/input.xml");
        Customer customer = (Customer) unmarshaller.unmarshal(xml);
 
        PhoneNumber primaryPN = customer.getPrimaryPhoneNumber();
        PhoneNumber otherPN1 = customer.getOtherPhoneNumbers().get(0);
        PhoneNumber otherPN2 = customer.getOtherPhoneNumbers().get(1);
        PhoneNumber otherPN3 = customer.getOtherPhoneNumbers().get(2);
        System.out.println(primaryPN == otherPN2);
        System.out.println(otherPN1 == otherPN3);
 
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setAdapter(new PhoneNumberAdapter());
        marshaller.marshal(customer, System.out);
    }
 
}


Output


Below is the output from running the demo code:

true
true
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer>
    <primary-phone-number id="B">555-BBBB</primary-phone-number>
    <other-phone-number id="A">555-AAAA</other-phone-number>
    <other-phone-number reference="B"/>
    <other-phone-number reference="A"/>
</customer>

 

From http://blog.bdoughan.com/2011/09/mixing-nesting-and-references-with.html

Nesting (computing) Element Object (computer science) Stack overflow Data (computing) Document Annotation Implementation Overflow (software)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Testing Level Dynamics: Achieving Confidence From Testing
  • The 5 Books You Absolutely Must Read as an Engineering Manager
  • 10 Things to Know When Using SHACL With GraphDB
  • Microservices Testing

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: