Posts Tagged ‘json’

Synchronous calls with REST Service

January 26th, 2011 No comments

In last posts , we had shown the example Creating your first REST service using Jersey. Then we introduced to making the Rest call from JavaScript.

The example which we had shown was for asynchronous request. Now let us assume that you want to make an asynchronous call . How will it work out ?

Option A : Let the call be asynchronous and put a while loop at the end

//Create a callback    for myRestService
myRestService.onreadystatechange = function()
if (myRestService.readyState == 4)
if(myRestService.status == 200)
// Retrieve the json object and work on it

var obj = JSON.parse(myRestService.responseText);

for(var i=0;i<obj.length;i++)
var item = obj[i];
‘<tr><td>’+ item.value1 + ‘</td>’ +
‘<td>’ + item.value2 + ‘</td>’ +


done = true;
else if(myRestService.status == 404)
alert(‘Error occurred:’ + myRestService.responseText);
alert(“No resposne–Error”);

tempresults = myRestService.send(null);
while(done == false){

//wait here


In this case you will see a warning pop up in Firefox

A script on this page may be busy, or it may have stopped responding. You can stop the script now, open the script in the debugger, or let the script continue.

Option Bfalse changes to true and we make synchronous calls“GET”, serviceUrl, true);

Now this works out well in IE but FF does not accept it.

Why it does not work ? Because we are still using the callback mechanism to get back the results

If we change it to regular method call , it will return results

Here is the code

<script type=”text/javascript” charset=”utf-8″ src=”json2.js”></script>
<script type=”text/javascript” charset=”utf-8″ src=”jquery-1.4.4.min.js”></script>

var restDataResults;
var done = false;

function callMyFirstRestService()
var myRestService = null;
if (window.XMLHttpRequest) //for mozilla
myRestService = new XMLHttpRequest();

if ( typeof myRestService.overrideMimeType != ‘undefined’)
else if (window.ActiveXObject) //for IE
myRestService = new ActiveXObject(“Microsoft.XMLHTTP”);

//This is the url/ restApp is the web app deployed on tomcat.
var serviceUrl = “″;“GET”, serviceUrl, false);
//synchronous calls
tempresults = myRestService.send();
var obj = JSON.parse(myRestService.responseText);


<h2>My First Rest Service</h2>

<p>My rest Service:
<input type=”button” id=”submitlookup” name=”submitlookup” value=”My First rest Service” onClick=”javascript:callMyFirstRestService();”/>

<div id=”divRestData” title=”My rest data”>
<table border=”1″>
<td width=’70’>Column A Heading</td>
<td width=’100′>Column B Heading</td>
<tbody id=’restDataResults’>

Hope you would have find this helpful.

Parsing JSON Results in Android

January 26th, 2011 8 comments

One of the common requirements for an android programmer is how to parse incoming JSON results from another web service or application into android. JSON is a data interchange format, and serves the same purpose as that of XML. XML is slowly being replaced by JSON because it’s easy to parse, light weight, and efficient too. We had talked about SOAP vs JSON earlier and not going to go into details again.

Let us focus on how to parse JSON results in Android.

We can parse JSON by 2 methods

i)  Using JSONObject and JSONTokener classes provided by Android SDK.
ii) Using external libraries. E.g GSON, Jackson etc.
(for more details refer

Let’s consider JSON data of the form:

“name”: “myName”,
“message”: [“myMessage1″,”myMessage2″],
“place”: “myPlace”,
“date”:  “thisDate”

Parsing JSON data using JSONTokener

class main extends Activity {


public void onCreate(Bundle savedInstanceState) {



try {

/* Inflate TextView from the layout */

TextView tv = (TextView)findViewById(;

/* JSON data considered as an example. Generally this data is obtained

from a web service.*/

String json = “{”

+ ”  \”name\”: \”myName\”, ”

+ ”  \”message\”: [\”myMessage1\”,\”myMessage2\”],”

+ ”  \”place\”: \”myPlace\”, ”

+ ”  \”date\”: \”thisDate\” ”

+ “}”;

/* Create a JSON object and parse the required values */

JSONObject object = (JSONObject) new JSONTokener(json).nextValue();

String name = object.getString(“name”);

String place = object.getString(“place”);

String date = object.getString(“date”);

JSONArray message = object.getJSONArray(“message”);

tv.setText(“Name: “+ name +”\n\n”);

tv.append(“Place: “+ place +”\n\n”);

tv.append(“Date: “+ date +”\n\n”);

for(int i=0;i<message.length();i++)


tv.append(“Message: “+ message.getString(i) +”\n\n”);


} catch (JSONException e) {e.printStackTrace();}

catch(Exception ex){ex.printStackTrace();}



Read more…

Categories: Programming / tutorials Tags: ,

Expose data in a JSON format through a Spring service

January 2nd, 2011 No comments

In our last post , we had talked about Create your first REST service  using JERSEY.

There are situations in which you would like your Spring services as web services. In this link below there is a code example of both REST and SOAP access the same backbone. Here is the link

Categories: Programming / tutorials Tags: ,

Goodbye SOAP – Welcome JSON REST

November 2nd, 2010 18 comments

We look at the leader to give us the guidance.

Not sure if that is quote or not but when Google , Apple , facebook or some of the best companies take some step, it is time to take notice.

Google has killed their SOAP API. XML+SOAP was a good milestone in the history of integration but it is now time to look at the next milestone and that next milestone is JSON+REST

What is REST ?

Representational State Transfer (REST) is a software architectural style for distributed hypermedia systems like the world wide web.

The term originated in a 2000 doctoral dissertation Architectural Styles and the Design of Network- based Software Architectures about the web written by Roy Fielding, one of the principal authors of the HTTP protocol specification, and has quickly passed into widespread use in the networking community.

What is SOAP ?

Simple Object Access Protocol . SOAP is an XML-based messaging protocol. It defines a set of rules for structuring messages that can be used for simple one-way messaging but is particularly useful for performing RPC-style (Remote Procedure Call) request-response dialogues. It is not tied to any particular transport protocol though HTTP is popular

Why REST + JSON is a good choice over SOAP? Read more…

Categories: Programming / tutorials Tags: , ,

Remote JSON made easy with jQuery

October 24th, 2010 1 comment

There are times when people resort to server side code instead of keeping code on client side to skip through voluminous JavaScript code and the additional technical logic that needs to be maintained.

One such scenario is when the JSON data for certain UI-related logic has to come from a different site. Due to restriction, this might not be possible with straight JavaScript. Here, the most favorite workaround is either to set up a proxy on the server side which calls the cross domain data and then use it on the client side, or move the handling of the logic complete to the server side. This is fine for certain not-so-popular sites with limited APIs. But not for Web 2.0-aware sites, especially for almost all of the social networking sites.

Why so? This is because, most of these sites offer a callback functionality whenever a URL is invoked requesting the data. While this would not make any difference for a browser to bypass the Same Origin Policy restriction, this could be utilized to a developer’s advantage. The callback-enabled URLs wraps the JSON data with a function. For example, consider this JSON data:








Read more…

Categories: Programming / tutorials Tags: ,

JSON Data Interchange Format – Approved by ECMA

October 16th, 2010 No comments

The Ecma General Assembly has approved the fifth edition of ECMAScript, according to Istvan Sebestyen, secretary general of the organization. Included in this new version of ECMAScript, of which the popular JavaScript is a dialect, is native support for using JavaScript Object Notation (JSON).

This inclusion “will certainly have a big impact on developers,” said Douglas Crockford, the Yahoo software architect cited as the creator of JSON.

“JSON is already pretty widely-used in Web applications. By having JSON built into the ECMAScript language, [JSON] implementations will get faster and safer,” Crockford said. The approval is also a sign that the Web application development community is edging away from using XML as the sole desired standard for exchanging data among disparate systems, in at least those cases where delivery of relatively simple structured data is required

Categories: Tech news Tags:

Understanding JSON Request

May 8th, 2010 3 comments

Continuing our JSON series, we have been covering some excellent features of JSON like JSON Java script tutorialJSON with CSS and Simple remoting using JSON. Today we will talk about JSON Request and its advantages


JSONRequest is a global JavaScript object. It provides three methods: post, get, and cancel. does an HTTP POST of a the serialization of a JavaScript object or array, gets the response, and parses the response into a JavaScript value. If the parse is successful, it returns the value to the requesting script. In making the request, no HTTP authentication or cookies are sent. Any cookies returned by the server cause the request to fail. The JSONRequest service can only be used to send and receive JSON-encoded values. JSONRequest cannot be used to retrieve other text formats. Read more…

Simple Remoting using JSON

May 4th, 2010 No comments

In our JSOn series in which we are covering some excellent features of JSON like  JSON with CSS and JSON Request. Today we will talk about JSON Remoting and its advantages

Simple Remoting using JSON

Simple Remoting is an open source Java library/framework which designed as an alternative SOA implementation. It uses JSON/HTTP(S)  as its transport protocol to access back end java components. Simple Remoting can convert POJO,Spring,EJB and other type of java objects to web services without any code change on existing classes by using simple xml declarations.

Features of Simple Remoting

  • It’s lightweight and requires no additional knowledge.
  • Build-in support for POJO, EJB2.1, EJB3 and Spring components. Framework is expandable so developers can implement additional locators as they need.
  • No programming and modification required to expose components as services. Simple xml declarations are enough.
  • Java & Java Script client implementations are out of the box. Client implementations are easily adaptable to .net and other popular languages
  • Services also can be reachable through regular HTTP POST/GET requests. You can access your EJB methods by entering a simple url to your browser Read more…