Using JSON with Codenvy


JSON Objects are created like simple key value pairs:

{
"pageInfo": { 
         "pageName": "abc", 
         "pagePic": "http://profile.ak.fbcdn.net/object2/367/65/q160119538822_4127.jpg" 
    } 
}

JSON is language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others.

The JSON format is often used for serializing and transmitting structured data over a network connection. It is used primarily to transmit data between a server and web application, serving as an alternative to XML.

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence. JSON filenames are saved with extension .json.

So here we are going to convert a .json file data to java Objects and read the complete name-value pairs in the .json file.


{ 
   "pageInfo": { 
         "pageName": "abc", 
         "pagePic": "http://profile.ak.fbcdn.net/object2/367/65/q160119538822_4127.jpg" 
    } 
    "posts": [ 
         { 
              "post_id": "160119538822_302076968822", 
              "actor_id": "1183856639", 
              "picOfPersonWhoPosted": "http://profile.ak.fbcdn.net/hprofile-ak-sf2p/hs302.ash1/23104_1183856639_4894_q.jpg" 
              "nameOfPersonWhoPosted": "Andrea Raquel", 
              "message": "Sounds cool. Can't wait to see it!", 
              "likesCount": "2", 
              "comments": [] 
              "timeOfPost": "1266036226" 
         } 
    ] 
} 
    

Create Java class

In the below java class we are reading the above .json file and parsing the data using JSON.SIMPLE parsing API. And iterate over the each and every key-value pair in the Entire JSON Object.

package com.jsonTest;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import org.json.simple.parser.ParseException;

public class JsonSimple {

	private static StringBuffer buffer=null;
	
	public static String convrtJson(String path) {
		buffer=new StringBuffer();
		JSONParser parser = new JSONParser();
		try {
			Object obj = parser.parse(new FileReader(path));
			JSONObject jsonObject = (JSONObject) obj;
			Set<String> set = jsonObject.keySet();
			for (String key : set) {
				Object ob = jsonObject.get(key);
				checkObject(ob);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return buffer.toString();
	}

	private static void printArray(Object ob) {
		JSONArray array = (JSONArray) ob;
		Iterator<JSONObject> iterator = array.iterator();
		while (iterator.hasNext()) {
			checkObject(iterator.next());
		}
	}

	private static void printMap(Object ob) {
		HashMap map = (HashMap) ob;
		for (Object str : map.keySet()) {
			printJSON(str, map.get(str));
		}
	}

	private static void checkObject(Object ob) {
		if (ob instanceof HashMap) {
			printMap(ob);
		} else if (ob instanceof JSONArray) {
			printArray(ob);
		}
	}

	private static void printJSON(Object key, Object value) {
		buffer.append(key + " - " + value+"<br/>");
		System.out.println(key + " - " + value);
	}
	
		
}

Specify project structure

The project structure :

project_structure

In the pom.xml we need to define the JSON.simple dependency as below

JSON.simple dependency

<dependency>
      <groupId>com.googlecode.json-simple</groupId>
      <artifactId>json-simple</artifactId>
      <version>1.1</version>
    </dependency>

Add jsp files

And we have two jsp files

1. index.jsp : where it has static json text displayed and will show the key value details of the json text below the static text after running the example.
2. calculate.jsp : this will invoke JsonSimple class method “convrtJson” by giving the test.json file path and captures the results and sent it to the index.jsp pade as below.

calculate.jsp


<%@ page language="java" import="java.util.*,javax.servlet.*" pageEncoding="ISO-8859-1"%>
<%@page import="com.jsonTest.JsonSimple"%>
<%
  String path = request.getContextPath();
  String basePath = request.getScheme() + "://"
  + request.getServerName() + ":" + request.getServerPort()
  + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'calculate.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
  <link rel="stylesheet" type="text/css" href="styles.css">
  -->

  </head>

  <body>
    <%
    String filepath=getServletContext().getRealPath("/WEB-INF/classes/" + "test.json");
      request.setAttribute("results",JsonSimple.convrtJson(filepath));
      RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
      rd.forward(request, response);
    %>
  </body>
</html>

In Index,jsp file we’ll read the data by getting the object in the request Attribute and iterate over the results .code is shown below.

Index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
  String path = request.getContextPath();
  String basePath = request.getScheme() + "://"
      + request.getServerName() + ":" + request.getServerPort()
      + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
  <link rel="stylesheet" type="text/css" href="styles.css">
  -->
  </head>

  <body>
    <form action="calculate.jsp" method="post">
      <center>
        <p>
          <font size="4" color="#808040"><em><strong><label>
                  Parsing the Below JSON Text :
                </label>
            </strong>
          </em>
          </font>
        <p />
          <p><font color="#0000a0" size="3" face="Courier New">{  
   &quot;pageInfo&quot;: {  
         &quot;pageName&quot;: &quot;abc&quot;,  
         &quot;pagePic&quot;: &quot;http://profile.ak.fbcdn.net/object2/367/65/q160119538822_4127.jpg&quot;  
    }  
    &quot;posts&quot;: [  
         {  
              &quot;post_id&quot;: &quot;160119538822_302076968822&quot;,  
              &quot;actor_id&quot;: &quot;1183856639&quot;,  
              &quot;picOfPersonWhoPosted&quot;: &quot;http://profile.ak.fbcdn.net/hprofile-ak-sf2p/hs302.ash1/23104_1183856639_4894_q.jpg&quot;  
              &quot;nameOfPersonWhoPosted&quot;: &quot;Andrea Raquel&quot;,  
              &quot;message&quot;: &quot;Sounds cool. Can't wait to see it!&quot;,  
              &quot;likesCount&quot;: &quot;2&quot;,  
              &quot;comments&quot;: []  
              &quot;timeOfPost&quot;: &quot;1266036226&quot;  
         }  
    ]  
}  
    </font></p>
              
          <button type="submit" name="Print Key Value">
            print Key-Value
          </button>
          <br /><p align="left">
          <em><font size="3" color="#0000ff"><% 
            if (request.getAttribute("results") != null) { 
              out.println(request.getAttribute("results")); 
            } 
          %></font></em>
        </p>
      </center>
    </form>
  </body>
</html>

Create web.xml

And finally the web.xml file. Which has only welcome file list configuration as shown below.

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Web Application Created With eXo IDE</display-name>
   <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>