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
Please enter at least three characters to search
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

  • Loading XML into MongoDB
  • Validate XML Request Against XML Schema in Mule 4
  • How to Convert JSON to XML or XML to JSON in Java
  • How to Connect to Splunk Through Anypoint Studio in 10 Steps

Trending

  • How Can Developers Drive Innovation by Combining IoT and AI?
  • AI-Driven Root Cause Analysis in SRE: Enhancing Incident Resolution
  • Developers Beware: Slopsquatting and Vibe Coding Can Increase Risk of AI-Powered Attacks
  • AWS to Azure Migration: A Cloudy Journey of Challenges and Triumphs
  1. DZone
  2. Coding
  3. Languages
  4. Binding to JSON & XML - Handling Collections

Binding to JSON & XML - Handling Collections

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

Join the DZone community and get the full member experience.

Join For Free
One of EclipseLink JAXB (MOXy)'s strengths is the ability to map an object model to both JSON and XML with a single set of metadata.  The one weakness had been that you needed to compromise on the JSON key or XML element for collection properties.  I'm happy to say that this issue has been solved in EclipseLink 2.5 (and EclipseLink 2.4.2), and I will demonstrate below with an example.

You can try this out today by downloading an EclipseLink 2.5.0 (or EclipseLink 2.4.2) nightly build starting on March 15, 2013 from:
  • http://www.eclipse.org/eclipselink/downloads/nightly.php

Domain Model 

By default a JAXB (JSR-222) implementation will not output a grouping element around collection data.  This can be done through the use of the @XmlElementWrapper annotation (see:  JAXB & Collection Properties).  This grouping element often has a plural name and is a better fit for the key of a JSON array than the repeating element defined by the @XmlElement annotation is.
package blog.json.collections;
 
import java.util.*;
import javax.xml.bind.annotation.*;
 
@XmlRootElement
@XmlType(propOrder={"name", "emailAddresses"})
public class Customer {
 
    private String name;
    private List<String> emailAddresses = new ArrayList<String>();
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    @XmlElementWrapper(name="email-addresses")
    @XmlElement(name="email-address")
    public List<String> getEmailAddresses() {
        return emailAddresses;
    }
 
    public void setEmailAddresses(List<'String> emailAddresses) {
        this.emailAddresses = emailAddresses;
    }
 
}
Demo

We will specify the JSON_WRAPPER_AS_ARRAY_NAME property with a true value to tell MOXy that it should use the grouping element as the name for the JSON array value.  Then we will use the same Marshaller to output the same object to both XML and JSON.
package blog.json.collections;
 
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.MarshallerProperties;
 
public class Demo {
 
    public static void main(String[] args) throws Exception {
        Customer customer = new Customer();
        customer.setName("Jane Doe");
        customer.getEmailAddresses().add("jane.doe@example.com");
        customer.getEmailAddresses().add("jdoe@example.org");
 
        Map<String, Object> properties = new HashMap<String, Object>(1);
        properties.put(MarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
        JAXBContext jc = JAXBContext.newInstance(new Class[] {Customer.class}, properties);
 
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
 
        // Output XML
        marshaller.marshal(customer, System.out);
 
        // Output JSON
        marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
        marshaller.marshal(customer, System.out);
    }
 
}
XML Output

Below is the XML output from running the demo code.  We see that email-addresses is marshalled as the grouping element which contains an email-address element for each item in the collection.
<?xml version="1.0" encoding="UTF-8"?>
<customer>
   <name>Jane Doe</name>
   <email-addresses>
      <email-address>jane.doe@example.com</email-address>
      <email-address>jdoe@example.org</email-address>
   </email-addresses>
</customer>
JSON Output

The following JSON output is produced from the same metadata.  The only difference is that we told MOXy to use the grouping element as the name for JSON array values.
{
   "customer" : {
      "name" : "Jane Doe",
      "email-addresses" : [ "jane.doe@example.com", "jdoe@example.org" ]
   }
}
JAX-RS 

You can easily use MOXy as your JSON-binding provider in a JAX-RS environment (see:  MOXy as your JAX-RS JSON Provider - MOXyJsonProvider).  You can specify that the grouping element should be used as the JSON array name with the wrapperAsArrayName property on MOXyJsonProvider.
package blog.json.collections;
 
import java.util.*;
import javax.ws.rs.core.Application;
import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider;
  
public class CustomerApplication  extends Application {
  
    @Override
    public Set<Class<?>> getClasses() {
        HashSet<Class<?>> set = new HashSet<Class<?>>(1);
        set.add(CustomerService.class);
        return set;
    }
  
    @Override
    public Set<Object> getSingletons() {
        MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider();
        moxyJsonProvider.setWrapperAsArrayName(true);
   
        HashSet<Object> set = new HashSet<Object>(1);
        set.add(moxyJsonProvider);
        return set;
    }
  
} 
Further Reading
If you enjoyed this post then you may also be interested in:
  • Binding to JSON & XML - Geocode Example
  • Binding to JSON & XML - Handling Null
  • Specifying EclipseLink MOXy as Your JAXB Provider




JSON XML Binding (linguistics)

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

Opinions expressed by DZone contributors are their own.

Related

  • Loading XML into MongoDB
  • Validate XML Request Against XML Schema in Mule 4
  • How to Convert JSON to XML or XML to JSON in Java
  • How to Connect to Splunk Through Anypoint Studio in 10 Steps

Partner Resources

×

Comments
Oops! Something Went Wrong

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:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!