Skip to main content

Notice: this Wiki will be going read only early in 2024 and edits will no longer be possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.

Jump to: navigation, search

Difference between revisions of "EclipseLink/UserGuide/MOXy/Mapping the Unmappable/Converters"

Line 31: Line 31:
  
 
   ...
 
   ...
 +
}
 +
</source>
 +
 +
Here, the '''Currency''' cannot be automatically mapped with JAXB because it does not contain a no-argument constructor.  However, we can write an adapter that will convert the '''Currency''' into something that JAXB does know how to handle - a simple '''String''':
 +
 +
<source lang="java">
 +
package example;
 +
 +
public class CurrencyAdapter extends XmlAdapter<String, Currency> {
 +
 +
  /*
 +
    *
 +
    */
 +
  public Currency unmarshal(String val) throws Exception {
 +
      return Currency.getInstance(val);
 +
  }
 +
 +
  public String marshal(Currency val) throws Exception {
 +
      return val.toString();
 +
  }
 +
 
}
 
}
 
</source>
 
</source>

Revision as of 16:04, 6 June 2011

EclipseLink MOXy

Eclipselink-logo.gif
EclipseLink
Website
Download
Community
Mailing ListForumsIRCmattermost
Issues
OpenHelp WantedBug Day
Contribute
Browse Source

XmlAdapter

JAXB's XmlAdapter can be used to map classes that would normally be considered "unmappable" - such as classes that do not have a default no-arg constructor, or classes for which an XML representation cannot be automatically determined. In a custom subclass of XmlAdapter, you can define define custom code to convert the unmappable class into something that JAXB can handle. Then, you can use the XmlJavaTypeAdapter annotation to indicate that your adapter should be used when working with the unmappable class.

Example

Our first example will use the following domain class:

package example;
 
import java.util.Currency;
 
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class PurchaseOrder {
 
   private Double amount;
 
   private Currency currency;
 
   ...
}

Here, the Currency cannot be automatically mapped with JAXB because it does not contain a no-argument constructor. However, we can write an adapter that will convert the Currency into something that JAXB does know how to handle - a simple String:

package example;
 
public class CurrencyAdapter extends XmlAdapter<String, Currency> {
 
   /*
    *
    */
   public Currency unmarshal(String val) throws Exception {
      return Currency.getInstance(val);
   }
 
   public String marshal(Currency val) throws Exception {
      return val.toString();
   }
 
}

Copyright © Eclipse Foundation, Inc. All Rights Reserved.