EclipseLink/Examples/MOXy/JSON Twitter

From Eclipsepedia

Jump to: navigation, search

JSON Binding and Twitter

In this example our JSON corresponds to the results of a query to get recent tweets about JAXB. We will use the Twitter Search API for this.

Twitter Query

Below is the URL corresponding to the search. We are looking for posts containing the word "jaxb", and want the result returned as JSON:

JSON Result

Below is an excerpt of the JSON returned from Twitter:

         "created_at":"Fri, 12 Aug 2011 09:00:26 +0000",
         "source":"<a href="" rel="nofollow">SOICHA</a>",
         "text":"How do you pronounce JAXB?: You know, URL is earl...",
         "created_at":"Fri, 12 Aug 2011 01:14:57 +0000",
         "source":"<a href="" rel="nofollow">twitterfeed</a>",
         "text":"How do you customise the XML output of Jersey JAXB serialization?",


The standard JAXB APIs are used the process the JSON message. Only two properties need to be set: "" to specify "application/json", and "eclipselink.json.include-root" to indicate there is no root node. These properties are set on the Marshaller and Unmarshaller. Since the JSON message does not contain a root node that can be used to determine the corresponding object type, we will leverage one of the Unmarshaller methods that lets us specify it.

package org.example;
import java.util.Date; 
import javax.xml.bind.*;
public class Demo {
    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(SearchResults.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        unmarshaller.setProperty("", "application/json");
        unmarshaller.setProperty("eclipselink.json.include-root", false);
        StreamSource source = new StreamSource("");
        JAXBElement<SearchResults> jaxbElement = unmarshaller.unmarshal(source, SearchResults.class);
        Result result = new Result();
        result.setCreatedAt(new Date());
        result.setText("You can now use EclipseLink JAXB (MOXy) with JSON :)");
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty("", "application/json");
        marshaller.setProperty("eclipselink.json.include-root", false);
        marshaller.marshal(jaxbElement, System.out);