Navigation
 
JSON Example Introduction
Sample JSON to XML Example

This page shows how to write a JSON Callback Servlet which processes an XML feed and turns it into a JSON Callback which can be processed by a piece of HTML.  The page contains a running example and the code which was written to achieve this.  The running example picks out JSON elements and displays them on the page from an XML feed which exists.
Sample JSON Portlet

Hello

Google AdSense
XML to JSON Example with code
This article contains the code for the example you see in the top window. 
The Portlet loads and calls a Servlet which loads an XML feed and turns it
into a JSON object.  That JSON object is consumed by the HTML of the
Portlet and displays the results.  This is a pure JSON callback.

The XML to JSON code


package xmltojson;

import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.fetcher.FeedFetcher;
import com.sun.syndication.fetcher.FetcherException;
import com.sun.syndication.fetcher.impl.FeedFetcherCache;
import com.sun.syndication.fetcher.impl.HashMapFeedInfoCache;
import com.sun.syndication.fetcher.impl.HttpURLFeedFetcher;
import com.sun.syndication.io.FeedException;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class XMLtoJSONServlet extends HttpServlet {

    FeedFetcherCache feedInfoCache;
    FeedFetcher feedFetcher;

    public void init()
    throws ServletException {
        feedInfoCache = HashMapFeedInfoCache.getInstance();
        feedFetcher = new HttpURLFeedFetcher(feedInfoCache);
    }

    protected void doGet(HttpServletRequest req,
            HttpServletResponse res)
            throws ServletException,
            IOException {
        String callback = req.getParameter("callback");
        String url = req.getParameter("url");
        if (callback==null)
            callback = "";
        if (url==null)
            url="http://mbradyie.googlepages.com/enginesunderursus.xml";
        PrintWriter out = res.getWriter();
        out.print(callback + "("+fetchFeed(url)+")");
    }

    private String fetchFeed(String url)
    throws IOException            {
        try {
            SyndFeed feed = feedFetcher.retrieveFeed(new URL(url));
            return syndFeed2JSON(feed);
        } catch (MalformedURLException e){
        } catch (FeedException e){
        } catch (FetcherException e){
        }
        return "Not working";
    }

    private String syndFeed2JSON(SyndFeed feed) {
        JSONObject jsonFeed = new JSONObject();
        try {
            String title = feed.getTitle();
            String link = feed.getLink();
            jsonFeed.put("title", title);
            jsonFeed.put("link", link);
            JSONArray jsonFeedEntries = new JSONArray();
            List entries = feed.getEntries();
            Iterator i = entries.iterator();
            while (i.hasNext()) {
                SyndEntry entry = (SyndEntry) i.next();
                String itemTitle = entry.getTitle();
                String itemLink = entry.getLink();
                JSONArray jsonFeedEntry = new JSONArray();
                jsonFeedEntry.put(itemTitle);
                jsonFeedEntry.put(itemLink);
                jsonFeedEntries.put(jsonFeedEntry);
            }
            jsonFeed.put("entries",jsonFeedEntries);
            return jsonFeed.toString();
        } catch (JSONException e) {
        }
        return "";
    }




The html calls the JSON API.  Note: This does not have to be Portlet code.  It can be
any html page.

<%@ taglib uri="http://java.sun.com/portlet" prefix="portlet" %>

<portlet:defineObjects />

<div id="myjsondiv"><p>Hello</p></div>

<script type="text/javascript">
function printJSON(jsonObj) {
var divCollection = document.getElementById('myjsondiv');
divCollection.innerHTML = '<ul><li>'+'RSS title:'+jsonObj.title+'</li>'+'<li>'+
'RSS link:'+jsonObj.link+'</li></ul>';
}
</script>

<script src="http://fooserver.com/samplexmltojson/xmltojson?url=
http://foo.googlepages.com/yoursample.xml&callba
ck=printJSON" type="text/javascript"></script>



The web.xml exposes the API.

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
    <display-name>XML to JSON Samples</display-name>

    <servlet>
        <servlet-name>FeedServlet</servlet-name>
        <servlet-class>xmltojson.XMLtoJSONServlet</servlet-class>
    </servlet>

    <servlet-mapping>
         <servlet-name>FeedServlet</servlet-name>
         <url-pattern>/samplexmltojson</url-pattern>
    </servlet-mapping>

</web-app>



You'll need to build your own xmltojson.war file and use the rome.jar
and its helper jar called rome-fetcher.jar


.
./META-INF
./META-INF/MANIFEST.MF
./WEB-INF
./WEB-INF/lib
./WEB-INF/lib/rome-fetcher.jar
./WEB-INF/lib/jdom.jar
./WEB-INF/lib/xmltojson.jar
./WEB-INF/lib/rome.jar
./WEB-INF/web.xml

Other Links

mbradyie.googlepages.com
googlepagestheadventure.blogspot.com
Sample JSON to XML Example

This page shows how to write a JSON Callback Servlet which processes an XML feed and turns it into a JSON Callback which can be processed by a piece of HTML.  The page contains a running example and the code which was written to achieve this.  The running example picks out JSON elements and displays them on the page from an XML feed which exists.
Sample JSON to XML Example

This page shows how to write a JSON Callback Servlet which processes an XML feed and turns it into a JSON Callback which can be processed by a piece of HTML.  The page contains a running example and the code which was written to achieve this.  The running example picks out JSON elements and displays them on the page from an XML feed which exists.