April 18, 2012

Extending JAXB - Representing Metadata as JSON

In previous posts I have described the XML mapping document and JSON-binding extensions in EclipseLink JAXB (MOXy).   Since MOXy has a JAXB model for its mapping document we were able to eat our own dog food, and now MOXy offers a JSON mapping document.

An external metadata representation is useful when:
  • You cannot modify the domain model (it may come from a 3rd party).
  • You do not want to introduce compile dependencies on JAXB APIs (if you are using a version of Java prior to Java SE 6).
  • You want to apply multiple JAXB mappings to a domain model (you are limited to one representation with annotations).
  • Your object model already contains so many annotations from other technologies that adding more would make the class unreadable.

Mapping File (binding.json)

The mapping file contains the same information as the JAXB annotations.  Like with annotations you only need to specify metadata to override default behavior.  The JSON mapping file can be used in place of, or in combination with the XML mapping file.  This JSON mapping file contains the same metadata as the XML mapping file from the following post:
{
   "package-name" : "blog.bindingfile",
   "xml-schema" : {
      "element-form-default" : "QUALIFIED",
      "namespace" : "http://www.example.com/customer"
   },
   "java-types" : {
      "java-type" : [ {
         "name" : "Customer",
         "xml-type" : {
            "prop-order" : "firstName lastName address phoneNumbers"
         },
         "xml-root-element" : {},
         "java-attributes" : {
            "xml-element" : [ 
                {"java-attribute" : "firstName","name" : "first-name"}, 
                {"java-attribute" : "lastName", "name" : "last-name"}, 
                {"java-attribute" : "phoneNumbers","name" : "phone-number"}
            ]
         }
      }, {
         "name" : "PhoneNumber",
         "java-attributes" : {
            "xml-attribute" : [ 
                {"java-attribute" : "type"}
            ],
            "xml-value" : [ 
                {"java-attribute" : "number"}
            ]
         }
      } ]
   }
}

Domain Model

The following domain model will be used in this example.  Because the JAXB metadata is represented as JSON, no annotations are used on the classes.

Customer 

package blog.bindingfile;

import java.util.List;
 
public class Customer {

    private String firstName;
    private String lastName;
    private Address address;
    private List<PhoneNumber> phoneNumbers;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public List<PhoneNumber> getPhoneNumbers() {
        return phoneNumbers;
    }

    public void setPhoneNumbers(List<PhoneNumber> phoneNumbers) {
        this.phoneNumbers = phoneNumbers;
    }

}

Address 

package blog.bindingfile;

public class Address {

    private String street;

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

}

PhoneNumber 

package blog.bindingfile;

public class PhoneNumber {
 
    private String type;
    private String number;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

}

JSON (input.json)

The following JSON input will be used in this example:

{
   "first-name" : "Jane",
   "last-name" : "Doe",
   "address" : {
      "street" : "123 A Street"
   },
   "phone-number" : [ {
      "type" : "work",
      "value" : "555-1111"
   }, {
      "type" : "cell",
      "value" : "555-2222"
   } ]
}

Demo Code

The JSON mapping file is passed in via the properties parameter when the JAXBContext is instantiated.

package blog.bindingfile;
 
import java.io.File;
import java.util.*;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
import org.eclipse.persistence.jaxb.JAXBContextFactory;

public class Demo {

    public static void main(String[] args) throws Exception {
        Map<String, Object> properties = new HashMap<String, Object>(3);
        properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, "blog/bindingfile/binding.json");
        properties.put("eclipselink.media-type", "application/json");
        properties.put("eclipselink.json.include-root", false);
        JAXBContext jc = JAXBContext.newInstance("blog.bindingfile", Customer.class.getClassLoader() , properties);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        StreamSource json = new StreamSource(new File("src/blog/bindingfile/input.json"));
        Customer customer = (Customer) unmarshaller.unmarshal(json, Customer.class).getValue();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(customer, System.out);
    }

}

Specifying the MOXy JAXB Implementation (jaxb.properties)

In order to use this extension, you must use MOXy as your JAXB provider.  To enable MOXy simply add a file named jaxb.properties in the same package as your domain classes with the following entry:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
 
Download the Source Code

The source code for this post is hosted on GitHub here.  You can download the source as a zip file here.

Further Reading

If you enjoyed this post you may also be interested in:
 

3 comments:

  1. I am not able to get the example working. I did created the entities in their package, created a jaxb.properties in the package. It throughs

    Internal Exception: org.xml.sax.SAXParseException: Content is not allowed in prolog.

    when creating an instance of JAXBContext. Any thoughts?

    ReplyDelete
    Replies
    1. I've updated this post with a section called "Download the Source Code". It contains links to obtain a running example. Please let me know if you need help getting that example to run.

      -Blaise

      Delete

Note: Only a member of this blog may post a comment.