Monday, July 16, 2012

JAXB XmlAdapter – Customized Marshaling and Unmarshaling

JAXB (Java Architecture for XML Binding), is an easy to use and efficient framework for working with XML documents in Java. A developer can easily convert an XML into Java objects (Unmarshaling) and vice versa (Marshaling) using JAXB. Although simple Java types (String, int) can be directly maps to XML types, sometimes a customized representation is required. For e.g. consider an XML snippet below

<config>
   <properties>
      <property name="name 1" value="value 1"/>
      <property name="name 2" value="value 2"/>
   </properties>
</config>

By default JAXB will bind it to the following Java object structure

@XmlRootElement
public class Config {
       @XmlElement (name="properties" type=Properties.class)     
        public Properties properties;
       …….
}

@XmlType
public class Properties {
        @XmlElement
       public List property;
       …………
}

@XmlType
public class Property {
      @XmlAttribute
       public String name;
       @XmlAttribute
       public String value;
       ……….
}

But imagine a scenario where you want the domain object to look like this

public class Config {
      public HashMap properties; //Map of property name and value
}

This is a typical case where you want to read an XML configuration file and maintain the properties in a Map.

To achieve this, you need a mechanism to intercept the default marshaling and unmarshaling of JAXB. And this can be done using XMLAdapter.

JAXB provides interceptors, in the form of XMLAdapters, to customize the marshaling and unmarshaling during binding. The below screen explains the concept.

Let’s consider the above example and see how can we achieve the expected output using adapters.

First of all, note that XMLAdapter is a customization on the top of default binding and hence the default classes, mentioned above, i.e. Config, Properties and Property need to be there. Now write a custom adapter. Customer adapters are provided with 2 parameters, one which JAXB will bind and one which you need as output of binding. Within adapter, you need to implement the logic of converting one to another. Here is how our custom adapter would look like.

public class CustomAdapter extends XmlAdapter> {
       @Override
       public Properties marshal(HashMap map) throws Exception {
              Iterator> itr = map.entrySet().iterator();
              ArrayList list = new ArrayList(map.entrySet().size());
              while (itr.hasNext()) {
                     Entry entry = itr.next();
                     Property property = new Property();
                     property.setName(entry.getKey());
                     property.setValue(entry.getValue());
                     list.add(property);
              }
              Poperties properties = new Properties();
              properties.setProperties(list);
              return properties;
       }
       @Override
       public HashMap unmarshal(Properties properties) throws Exception {      
              List list = properties.getProperties();      
              HashMap map = new HashMap(list.size());
              for (Property property : list) {               
                  map.put(property.getName(), property.getValue());
              }
              return map;
       }
}

Along with this, now we need to change the root element class a bit, since we want the Hashmap as the value holder now.
@XmlRootElement
public class Config {      
       @XmlJavaTypeAdapter (CustomAdapter.class)
       @XmlElement (name="properties", type=Properties.class)
       private HashMap properties;
       ………………
}

Now write a method to test the unmarshaling.

public void testUnmarshal() {
       try {
              JAXBContext context = JAXBContext.newInstance(Config.class);
              Config config = (Config) context.createUnmarshaller().unmarshal(new File("config.xml"));
              Iterator> itr = config.getProperties().entrySet().iterator();
              while (itr.hasNext()) {
                     Entry entry = itr.next();
                     System.out.println(entry.getKey() + "  " + entry.getValue());
              }                   
       } catch (JAXBException e) {
              e.printStackTrace();
       }
}

The output of the above test method would be
name 1   value 1
name 2   value 2


Conclusion: JAXB provides XMLAdapters as a way to the developer to intercept the marshaling and unmarshaling process and write code to custom mappings.

11 comments:

tamilsasi said...

After reading this web site I am very satisfied simply because this site is providing comprehensive knowledge for you to audience.
Thank you to the perform as well as discuss anything incredibly important in my opinion. We loose time waiting for your next article writing in addition to I beg one to get back to pay a visit to our website in



selenium training in Bangalore
selenium training in Marathahalli
selenium training in Btm layout
selenium training in Jaya nagar
selenium training in Electronic city
selenium training in Kalyan nagar



Unknown said...

You made such an interesting piece to read, giving every subject enlightenment for us to gain knowledge. Thanks for sharing the such information with us
python training in chennai
Python Online training in usa
python course institute in chennai

rocky said...

I want read this article. Is very nice content.
Python Training in Chennai

Python Training in Bangalore

Python Training in Hyderabad

Python Training in Coimbatore

Python Training

python online training

python flask training

python flask online training

Jayalakshmi said...

I think this article will fully complement you. Please continue publishing helpful topics like this Regards,from
data science training in chennai

data science training in tambaram

android training in chennai

android training in tambaram

devops training in chennai

devops training in tambaram

artificial intelligence training in chennai

artificial intelligence training in tambaram

praveen said...

Wonderful blog with great piece of information. Regards to your effort. Keep sharing more such blogs.Looking forward to learn more from you.
hardware and networking training in chennai

hardware and networking training in porur

xamarin training in chennai

xamarin training in porur

ios training in chennai

ios training in porur

iot training in chennai

iot training in porur

shiny said...

Regards to your effort. Keep sharing more such blogs.Looking forward to learn more from you.


data science training in chennai

data science training in annanagar

android training in chennai

android training in annanagar

devops training in chennai

devops training in annanagar

artificial intelligence training in chennai

artificial intelligence training in annanagar

Sarthak Yadav said...

Good Post! , it was so good to read and useful to improve my knowledge as an updated one, keep blogging.After seeing your article I want to say that also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts likethis. https://www.3ritechnologies.com/course/angular-js-training-institute-in-pune/

Meghana said...

Sandpaper Market Factors, Opportunities to register a healthy growth rate Forecast 2022-2028
Summary

A New Market Study, Titled “Sandpaper Market Upcoming Trends, Growth Drivers and Challenges” has been featured on fusionmarketresearch.

This report provides in-depth study of ‘Sandpaper Market ‘using SWOT analysis i.e. strength, weakness, opportunity and threat to Organization. The Sandpaper Market report also provides an in-depth survey of major market players which is based on the various objectives of an organization such as profiling, product outline, production quantity, raw material required, and production. The financial health of the organization.

Sandpaper Market

James said...

Hexachlorodisilane Market Status (2016-2020) and Forecast (2021E-2028F) by Region, Product Type & End-Use
HEXACHLORODISILANE MARKET

Market Overview

At the beginning of a recently published report on the global Hexachlorodisilane Market, extensive analysis of the industry has been done with an insightful explanation. The overview has explained the potential of the market and the role of key players that have been portrayed in the information that revealed the applications and manufacturing technology required for the growth of the global Hexachlorodisilane Market.

Hexachlorodisilane Market

Mohitmrc said...
This comment has been removed by the author.
Mohitmrc said...


The Java Enterprise Platform (JEE) is a collection of technologies and standards that provide a framework for developing and deploying enterprise-level applications. It is designed to help organizations create and maintain large-scale, distributed, and high-performance applications that can run on a variety of platforms.


https://www.technobridge.in/clinical-research-course.html