August 19, 2011

Binding to JSON & XML - Geocode Example

In a previous post I introduced the JSON binding that was added in the MOXy component in EclipseLink 2.4.  In that post I explained how the same metadata that is used for XML binding can be directly applied to JSON binding.  In this post I will demonstrate how powerful this is, by mapping one object model to both XML and JSON using the same set of metadata.  Google Maps Geocoding API V2 will be used to provide the XML and JSON inputs for this example.

You can try this out now using a download available from:

XML Input

Below is the link we will use to get the data as XML.  This is specified in the output parameter.


<?xml version="1.0" encoding="UTF-8" ?>
<kml xmlns="">
  <name>1600 Amphitheatre Parkway, Mountain View, CA</name>
  <Placemark id="p1">
   <address>1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA
   <AddressDetails Accuracy="8"
       <LocalityName>Mountain View</LocalityName>
        <ThoroughfareName>1600 Amphitheatre Pkwy</ThoroughfareName>
    <LatLonBox north="37.4227454" south="37.4200474" east="-122.0843863"
     west="-122.0870843" />

JSON Input

Below is the link we will use to get the data as JSON.  This is specified in the output parameter.


  "name": "1600 Amphitheatre Parkway, Mountain View, CA",
  "Status": {
    "code": 200,
    "request": "geocode"
  "Placemark": [ {
    "id": "p1",
    "address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
    "AddressDetails": {
   "Accuracy" : 8,
   "Country" : {
      "AdministrativeArea" : {
         "AdministrativeAreaName" : "CA",
         "Locality" : {
            "LocalityName" : "Mountain View",
            "PostalCode" : {
               "PostalCodeNumber" : "94043"
            "Thoroughfare" : {
               "ThoroughfareName" : "1600 Amphitheatre Pkwy"
      "CountryName" : "USA",
      "CountryNameCode" : "US"
    "ExtendedData": {
      "LatLonBox": {
        "north": 37.4227454,
        "south": 37.4200474,
        "east": -122.0843863,
        "west": -122.0870843
    "Point": {
      "coordinates": [ -122.0857353, 37.4213964, 0 ]
  } ]

Domain Model

The following domain model will be used for this example.  Note that the exact same class with the exact same metadata will be used for both the XML and JSON bindings.


package blog.geocode.json;

import javax.xml.bind.annotation.XmlType;
import org.eclipse.persistence.oxm.annotations.XmlPath;

@XmlType(propOrder={"country", "state", "city", "street", "postalCode"})
public class Address {

    private String street;

    private String city;

    private String state;

    private String country;

    private String postalCode;



The @XmlSchema annotation is used to configure the namespace information.  These namespaces will be ignored when the JSON binding is performed.

package blog.geocode.json;

import javax.xml.bind.annotation.XmlAccessorType;


The following code will be used to convert the XML and JSON messages to/from objects.  Somethings to note about this code:
  1. Only one JAXBContext is created, this means only one set of initialized metadata.
  2. Only Java SE 6 imports are required.
  3. The same instances of Marshaller and Unmarshaller are used for both the XML and JSON binding.  JSON binding was enabled by setting the "" property to "application/json" (lines 25 and 29).  We also set the "eclipselink.json.include-root" property to false to indicate there is no root node (lines 26 and 30).
  4. A StAX parser is used to navigate to a local root that is comparable with the JSON structure.
package package blog.geocode.json;
import javax.xml.bind.*;
public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Address.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        // XML
        XMLInputFactory xif = XMLInputFactory.newInstance();
        StreamSource xml = new StreamSource(",+Mountain+View,+CA&output=xml&sensor=false&key=YOUR_KEY_HERE");
        XMLStreamReader xsr = xif.createXMLStreamReader(xml);
        xsr.nextTag(); // Advance to kml tag
        xsr.nextTag(); // Advance to Response tag
        JAXBElement<Address> addressFromXML = unmarshaller.unmarshal(xsr, Address.class);
        marshaller.marshal(addressFromXML, System.out);

        // JSON
        unmarshaller.setProperty("", "application/json");
        unmarshaller.setProperty("eclipselink.json.include-root", false);
        StreamSource json = new StreamSource(",+Mountain+View,+CA&output=json&sensor=false&key=YOUR_KEY_HERE");
        JAXBElement<Address> addressFromJSON = unmarshaller.unmarshal(json, Address.class);
        marshaller.setProperty("", "application/json");
        marshaller.setProperty("eclipselink.json.include-root", false);
        marshaller.marshal(addressFromJSON, System.out);


XML Output

<?xml version="1.0" encoding="UTF-8"?>
<Response xmlns="" xmlns:ns="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0">
                  <ns:LocalityName>Mountain View</ns:LocalityName>
                     <ns:ThoroughfareName>1600 Amphitheatre Pkwy</ns:ThoroughfareName>

JSON Output

   "Placemark" : {
      "AddressDetails" : {
         "Country" : {
            "CountryNameCode" : "US",
            "AdministrativeArea" : {
               "AdministrativeAreaName" : "CA",
               "Locality" : {
                  "LocalityName" : "Mountain View",
                  "Thoroughfare" : {
                     "ThoroughfareName" : "1600 Amphitheatre Pkwy"
                  "PostalCode" : {
                     "PostalCodeNumber" : "94043"

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, then you may also be interested in:

No comments:

Post a Comment

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