Node.js


From Wikipedia, the free encyclopedia
  (Redirected from Nodejs)

Node.js is a software system designed for writing highly-scalable internet applications, notably web servers.[1] Programs are written inJavaScript, using event-driven, asynchronous I/O to minimize overhead and maximize scalability.[2] Node.js consists of Google's V8 JavaScript engine plus several built-in libraries.
Node.js was created by Ryan Dahl starting in 2009, and its growth is sponsored by Joyent, his employer.[3][4]
Similar environments written in other programming languages include Twisted for Python, Perl Object Environment for Perl, libevent for C and EventMachine for Ruby. Unlike most JavaScript, it is not executed in a web browser, but is instead a form of server-side JavaScript. Node.js implements some CommonJS specifications.[5] Unlike most JavaScript systems, it provides a REPL environment for interactive testing.

Examples

This is a complete implementation of hello world as a HTTP Server in Node.js:
var http = require('http');
 
http.createServer(function (request, response) {
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end('Hello World\n');
}).listen(8000);
 
console.log('Server running at http://127.0.0.1:8000/');

This is a simple TCP server which listens on port 7000 and echoes 'hello' upon connection:
var net = require('net');
 
net.createServer(function (stream) {
    stream.write('hello\r\n');
 
    stream.on('end', function () {
        stream.end('goodbye\r\n');
    });
 
    stream.pipe(stream);
}).listen(7000);

[edit]Community

Node.js has a active developer community primarily centered on two mailing lists, nodejs and nodejs-dev, and the IRC channel #node.js on freenode. The community gathers atNodeConf, an annual developer conference focused on Node.js.[6]

Why Everyone Is Talking About Node


On the 20th floor of a San Francisco skyscraper, a handful of developers are working on a new technology that’s changing the way real-time web apps are built and how they scale.
This technology, called Node.js, is being hailed as “the new Ruby on Rails” by some in the developer community. But it’s not a magic bullet, nor is it appropriate for all programming scenarios.
Joyent, an SF-based cloud software company, is sponsoring the growth and development of Node. It employs Node creator Ryan Dahl, hosts events and creates tools for the growing Node community. Recently, Mashablevisited Joyent to see demos from three startups that are using Node to build web and mobile apps for consumers.
In the process, we learned a lot about how and why Node works for the real-time web — and how Node is changing the way the developer community creates the Internet as we know it.

What Makes Node Different


Node had a watershed year in 2010, and it’s shaping up to be as popular as Ruby on Rails among developers. Since the framework was built for the commonly used JavaScript, the barriers to entry are remarkably low, and the reasons for choosing Node to build apps — especially low-latency, real-time apps — are increasingly compelling.

Then there’s the community. The Ruby community has been criticized for being exclusive and harsh. The Node community provides a welcome contrast and embodies the spirit of many other open-source communities. Again, the framework’s JavaScript roots means that it appeals to the less hacker-ish web designer who might be dabbling in web app development as much as it appeals to longtime, hardcore hackers who simply want a better way to build real-time apps.
We asked each of the three startups giving demos at Joyent: Why choose Node?
The common wisdom among many developers is that there is no single right language or framework that should and must be used for all web apps. But based on what we heard from these startups, Node is increasingly being seen as a “best solution” for a certain type of application.
According to Tom Hughes-Croucher, a recent Joyent hire who is writing the first O’Reilly book on Node, “Node has popularized event-driven programming.” With event-driven programming, Hughes-Croucher explains, “The actual amount of resources you use is much smaller, and you can get a lot more out of fewer servers.”
Node is all about making event-driven, low-latency, concurrent apps. Erlang, the language that powers Facebook’s chat server, uses the same model. Tornado, a concurrent server for Python that powers FriendFeed, was an attempt at this, too. But Node has one advantage over technologies like Erlang and Tornado: “None of that was too accessible,” says Hughes-Croucher. “Node takes a language people know very well — Javascript — and makes it available to do server programming, as well.”
In traditional languages and frameworks, the communication inside the app between the web server and the database is the most time-intensive part of the transaction. Node makes a much smaller footprint on your web server. It allocates web server resources on an as-needed basis, not pre-allocating a large chunk of resources for each user. For example, Apache might assign 8MB to a user, while Node assigns 8KB.
“The way that Node is more efficient on servers is by not allocating resources to things while it waits,” says Hughes-Croucher. “Say you have to talk to the database, and that’s going to take 50ms to respond. Instead of assigning all of the processing resources for that 50ms wait, it just uses a placeholder. When the database responds, then it allocates the resources needed to process. That means it’s totally possible to do a lot more requests at once, because you only allocate the server resources when you need to use them, not while you are waiting on databases.”

Node’s Explosive Growth


Unlike PHP or Ruby, Node has yet to appear as the technological face of a popular, mass-adopted web service like Twitter, WordPress or Facebook.
Rather, Node took off in the imaginations of programmers, organically becoming the quirky new tech that was on the tip of every tongue. First, devs asked if you’d heard of it; then, they started asking if you’d tried it or built anything with it.
As you can see from these GitHub reports, both the number of committers and the number of commits to Node core really took off, and there are no signs of Node’s growth slowing down in the dev community.

Commits and committers to Node on GitHub peaked in the fall of 2010, but developers’ conversations around Node have really just started to pick up steam since the beginning of 2011. Here’s a graph showing Twitter conversations around Node; you’ll notice a few spikes throughout the fall of 2010, and more consistent conversations occurring in 2011.
If you look at Rails and Node on GitHub and compare the traffic,” says Hughes-Croucher, “Rails had 270,000 views over the past three months. Node has 325,000, and it’s only going up… it’s exploding.”
There have been “it” technologies in the past, and the current vogue is Ruby on Rails. So what makes devs think Node is the heir apparent?
“Node is going to become the next big thing for a few reasons,” said Hughes-Croucher. “Everyone wants to do way more powerful apps — things like Google Instant and Facebook. People are expected to support millions of users on a ton of devices in real time. These are the expectations people have of applications now. And if you did that with traditional frameworks, it would take forever, and the hardware would cost millions of dollars.
“The point of Node is that it’s really fast, it’s really easy to scale, and the Javascript aspect means it’s really easy to build.”

Node for Real-Time Voice


Igal Perelman is the VP of product for Voxer, an iOS app that aims to “make audio sexy again.” It functions a bit like a walkie-talkie, a bit like a group IM app and a bit like a social/location consumer app.
“There is a huge reason why kids love to use walkie-talkies. It’s fun and immediate,” said Perelman. “We took that basic use case and improved it a lot.”
The user pushes a button, starts talking, and the message is immediately sent to the app user on the other end. Both parties can listen and talk simultaneously. Chat requests come through as push notifications, allowing the users to choose whether or not to join the chat.
Users can also re-listen to messages in case they need clarification or missed part of a message, like rewinding a video. Another cool feature: The app supports group chats with unlimited numbers of participants.
Finally, it’s entirely free.
Voxer uses Node because the low latency allows for near-instant transfer of audio data. Says Perelman: “Node was very crucial to this, because the audio needed to be live. And Node allows us to maintain a large number of connections with very low latency. It was a quite easy decision.”
Voxer’s VP of technology, Matt Ranney, told us (via the app itself, of course), “This is our third iteration trying to do live voice. We first tried C++ for performance reasons, but it was too complicated, too hard to wrangle. Next, we chose Python. It was great, but unfortunately, the Python virtual machine is incredibly slow.
“So we’ve gone to the opposite extreme. In our third version, we’ve done it in Node, and we have the best of both worlds. We have the high-level language of Javascript and the high performance of the [Google's V8 JavaScript engine's] virtual machine.”

Node for Gaming


One of the hackathons we followed this year was Node Knockout, a 48-hour contest to see who in the world can build the best, most complete, most interesting Node apps on a very tight deadline.
The popularity winner for the 2010 contest was Scrabb.ly, a massively multiplayer online version of Scrabble. The game plays in real time, and the map of all the tiles is sprawling to gargantuan proportions.
The team built the game in two days and has since made a company out of the project.
On the flipside, “Rails Rumble [a similar, Ruby-on-Rails-flavored hackathon] has been around for four or five years, and only one company has come out of it,” says Fortnight Labs and Node Knockout co-founder Gerad Suyderhoud. “We had a company in our first year. Because Node is such a great technology for real-time web apps, you see a lot more games, so the results are a lot more fun.” The next Node Knockout is in August 2011.
Suyderhoud and co-founder Visnu Pitiyanuvath’s entry in the 2009 Rails Rumble was Lazeroids, but they discovered that building a real-time game in RoR was “too hard.”
When it comes to real-time games, says Suyderhoud, “There’s really not a lot that’s competing with [Node]. The other technologies just aren’t as good at doing real time. They’re backed in older frameworks. Node was designed from the ground up for real time and to be easy to use. Other technologies would take forever to do the same things.”
“You have this giant ecosystem of Javascript that’s perfect for real time,” he adds.
And as far as community is concerned, Suyderhoud says, “it’s amazing how inclusive it is. I’ve never seen such good support. For Node Knockout, it was some people’s first time using Node. We didn’t provide a lot of support, but we got really lucky. A lot of people who had no vested interest and were not participants stepped up and helped people solve their problems over the weekend, in chat channels and over Twitter. I was definitely not expecting that.”

Node for Collaboration


Mockingbird is more a tool for web designers than a true consumer app, and it allows devs and designers to rapidly create wireframes. The interesting thing about Mockingbird is that this Node.js app is already making serious money for its creators.
Basically, Mockingbird is a tool for collaborative drawing and real-time communication between designers and clients. It took the founders just months to take the app from concept to a working beta.
“We’ve been around since November of 2009 and launched our paid product November 2010,” says CTO and co-founder Saikat Chakrabarti. “We’re doing much better than we thought. We thought we’d be struggling entrepreneurs for a long time, but we’re very much in the green.”
The app currently has 60,000 users and hosts more than 100,000 projects.
Says Chakrabarti: “I tried to do the app in Twisted and Tornado at the time, and Node was by far the easiest… A lot of people and companies are very invested in this.”

Node for the Future


Time will prove whether Node is that next big thing, but one thing was agreed upon by all parties at this roundtable demo session: Node needs a Twitter, a Facebook or some other big, consumer-friendly, mass-adopted app to make the mainstream tech community take notice.
However, as soon as middle managers get wind of Node, it runs the risk of developing a bubble. An employment bubble would surely be followed by an employment crash, which would likely be perceived as the “downfall of Node.”
A misunderstanding of the technology is also a risk. Former Twitter engineer Alex Payne’s claim that Ruby was slow continues to haunt general conversations about Ruby to this day.
It’s not our intention to inflate anyone’s expectations of Node. And we’re certainly not advocating its use for all programming projects. However, we do think that Node is an interesting, accessible and efficient technology for real-time applications, and we’d love to see what comes of this framework.
We’ll especially be keeping an eye out for “the Twitter of Node” — both to critically examine how the framework performs under pressure and to keep an eye out for hype.
Stay tuned for Mashable‘s ongoing coverage of Node, including one-on-one interviews and code snippets to get you started.

Google Maps Query String Parameters

The following is a list of query string parameters that can be passed to Google Maps. These arguments are helpful if you want to get Google Maps to display driving directions, which are not available under the API.



Query

Translation

q=“q” stands for “query” and anything passed in this parameter is treated as if it had been typed into the query box on the maps.google.com page.
EX.

http://maps.google.com/?q=New+York
near=“near” can be used as the location part of a query instead of putting the entire string into q=. Also needed/useful for disambiguation.
EX.

http://maps.google.com/?q=shelton;near=new+york
http://maps.google.com/?q=shelton;near=seattle
g=“g” is an address or location that provides extra context for the “q” parameter. Google Maps stores the last run search here, but if it is the first search it can only contain your starting location. This is a potential information leak, so make sure you do actually mean to share the content of this parameter.
mrt=“mrt” specifies a type of search. The default is blank, which searches for everything. Other options are:
  • mrt=yp  –  Yellow pages
  • mrt=realestate — real estate listings
  • mrt=ds — Related maps
  • mrt=websearch  — local web pages (synonym for ‘yp’ ?)
  • mrt=loc — Locations search
Many uses will require the ‘q’ option and/or the ‘near’ option
EX.

http://maps.google.com/?q=phoenix&mrt=yp&near=tempe
start=“start” skips the first (start-1) matches.
num=“num” displays, at most, the given number of matches. The valid range is 0 to 20.
ll=“ll” stands for Latitude,longitude of a Google Map center – Note that the order has to be latitude first, then longitude and it has to be in decimal format.
sll=“sll” Latitude,longitude of the point from which the business search should be performed.
spn=“spn” Approximate lat/long span. The zoom level will be adjusted to fit if there’s no z= parameter.
latlng=“latlng” takes three numbers separated by commas. The first two numbers (presumably representing latitude and longitude multiplied by 1000000) are ignored. The third number seems to be a Google internal “Company ID” number for a particular business.
cid=“cid” is similar to “latlng,” but generating a different map size. It takes three numbers separated by commas. The first two numbers (presumably representing latitude and longitude multiplied by 1000000) are ignored. The third number seems to be a Google internal “Company ID” number for a particular business.
geocode=“geocode” is a concatination of “geocode” encoded values for waypoints used in directions.
radius=“radius” localizes results to a certain radius. Requires “sll” or similar center point to work.
t=“t” is Map Type. The available options are “m” map, “k” satellite, “h” hybrid, “p” terrain.
z=“z” sets the zoom level.
layer=“layer” Activates overlay. Current option is “t” traffic.
lci=“lci” activates layers of tiles and needs to be comma-separated.
view=“view” can be used to select text view (view=text) or the normal map view (view=map).
saddr=“saddr” source address. Use this when asking for driving directions.
daddr=“daddr” Destination address(es). Use this when asking for driving directions.
mrad=“mrad” gives you additional destination address.
dirflg=“dirflg” is the route type: dirflg=h Switches on “Avoid Highways” route finding mode. dirflg=t Switches on “Avoid Tolls” route finding mode. dirflg=r Switches on “Public Transit” – only works in some areas. dirflg=w Switches to walking directions – still in beta.
via=“via” gives a comma separated list of intermediate addresses for directions, that should be ‘via points’.
doflg=“doflg” Distance Units. (Defaults to prevalent units in country of origin.) doflg=ptk outputs directions in metric (km) and doflg=ptm outputs directions in imperial (miles).
cbll=“cbll” is latitude,longitude for Street View.
cbp=“cbp” Street View window that accepts 5 parameters: 1) Street View/map arrangement, 11=upper half Street View and lower half map, 12=mostly Street View with corner map 2) Rotation angle/bearing (in degrees) 3) Tilt angle, -90 (straight up) to 90 (straight down) 4) Zoom level, 0-2 5) Pitch (in degrees) -90 (straight up) to 90 (straight down), default 5
panoid=“panoid” is the panorama ID, which is the ID of the current nearby panorama object in Street View.
hl=“hl” stands for “host language”.
om=“om” stands for “overview map.” The presence of this parameter with a value other than 1 causes the overview map to be closed. If the parameter is omitted, or present with the value 1, then the overview map is open.
ie=“ie” stands for “input encoding” and can be used to specify the input character encoding set.
oe=“oe” stands for “output encoding” and can be used to specify the input character encoding set.
output=“output” is for output format (blank is default).
f=“f” stands for “form” and controls the style of query form to be displayed. f=d Displays the “directions” form (two input boxes: from, to). f=l Displays the “local” form (two input boxes: what, where). f=q (or no parameter) The default search form is displayed (single input).
pw=“pw” stands for “print window.” It activates the print mode and initiates printing. Example, pw=2.
iwloc=“iwloc” stands for “info window location” and specifies where the infowindow will be displayed. In a business search iwloc=A to iwloc=J will open the info window over the corresponding business marker, and iwloc=near will place it over the big green arrow if that’s currently displayed. iwloc=addr can be used on map search to explicitly request the info window to be open on the address, but that’s the default anyway. Directions search supports iwloc=start, iwloc=end and iwloc=pause1
iwd=1“iwd” stands for “info window display” and specifies that the infowindow displayed (iwloc=) will be a detailed (expanded) view.
iwstate1=iwstate1=ssaddfeatureinstructioncard Specifies that the infowindow is in add place mode. Use with ssp=addf and iwloc=SS.  iwstate1=sscorrectthiscard Specifies the infowindow is in edit mode. iwstate1=sscorrectthiscard:ssmovemarkercard The infowindow is in Move marker mode, with the marker bouncing and draggable. iwstate1=sscorrectthiscard:ssedithistorycard The infowindow is in View history mode, displaying a graphical list of marker moves.
msa=“msa” is involved in My Maps processing. It does nothing without the “/ms” and “/ms” does nothing without the msa=. msa=0 Used with msid= to show a particular My Map.
msa=b Activates the “My Maps” sidebar when used in conjunction with “maps.google.com/ms”.  msa=1 shows the My Maps tab directly (like msa=b did). msa=2 Jumps directly to create new My Map form.
msid=“msid” specifies a My Maps identifier. When used in conjunction with “maps.google.com/ms” and msa=0, the corresponding My Map is displayed.
vp=“vp” stands for “view point” and the presence of this parameter causes maps.google.com to switch into Copyright Service mode. Instead of returning the html that draws a map, it returns information about the copyright ownership in Javascript format. The vp= parameter specifies the viewpoint (i.e. the centre of the map). Copyright Service only works when the spn= and z= parameters are also supplied, indicating the span and the zoom. Optional parameters are t=, which specifies the map type, and key= which specifies the API key of the site performing the request.
sspn=“sspn” stands for “Screen span”. Map bounds dimensions in Degrees, to calculate this use:newGLatLng(map.getBounds().getNorthEast().lat() − map.getBounds().getSouthWest().lat(),map.getBounds().getNorthEast().lng() − map.getBounds().getSouthWest().lng()).toUrlValue()
Thanks to Google Maps Parameters Guide from MapKi for this great resource!

Android: Deserialize both XML and JSON


When I first started learning Android, I was curious in making service calls and handling the results.  Naturally, I wanted to see code snippets involving
  • parsing XML
  • deserializing JSON
To my surprise, most snippets I found only demonstrated XML parsing, with fewer demonstrating JSON deserialization.  Therefore, I decided to post these brief snippets in hopes they are useful to folks.
We’ll use a simple Employee class as an example.  If you are familiar with the term DTO, data transfer object, this Employee class represents a simple DTO.  The Java source code is as follows:
public class Employee {
    public long Id;
    public long DeptId;
    public long SalaryGradeId;
    public String FirstName;
    public String LastName;
    public String Email;
    public String Phone;
    public String Title;
    public boolean TakesLongLunches;
}

And we’ll use the following ResourceHelper class to request a list of employees:
package com.demo.helpers;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class ResourceHelper {
    public static String loadManySerialized(String url)
    {
        HttpClient httpclient = new DefaultHttpClient();

        // Prepare a request object
        HttpGet httpget = new HttpGet(url);

        // Execute the request
        HttpResponse response;

        String result = null;
        try {
            response = httpclient.execute(httpget);

            // Get hold of the response entity
            HttpEntity entity = response.getEntity();
            // If the response does not enclose an entity, there is no need
            // to worry about connection release

            if (entity != null) {
                // A Simple Response Read
                InputStream instream = entity.getContent();
                result = convertStreamToString(instream);

                // Closing the input stream will trigger connection release
                instream.close();
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return result;
    }

    private static String convertStreamToString(InputStream is) {
        /*
        * To convert the InputStream to String we use the BufferedReader.readLine()
        * method. We iterate until the BufferedReader return null which means
        * there's no more data to read. Each line will appended to a StringBuilder
        * and returned as String.
        */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8192);
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    } 
}

And here are two calls to ResourceHelper;  one requesting the response in XML format, and the other requesting the response in JSON:
String XMLSerializedResources = ResourceHelper.loadManySerialized("http://demos.brianbuikema.com/apps/soa_services/employees?format=XML"); 
String JSONSerializedResources = ResourceHelper.loadManySerialized("http://demos.brianbuikema.com/apps/soa_services/employees?format=JSON");
Next, we’ll parse the XML list within the Employee Repository with the help of an XMLHelper class (see line 24).  The XMLHelper class, also shown below, calls the ResourceHelper class we discussed earlier.

package com.demo.domainmodel.repository;

import java.io.IOException;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import com.demo.domainmodel.Employee;
import com.demo.helpers.XmlHelper;

public class EmployeeRepository
{
    public static ArrayList<Employee> loadMany(String url)
    {
        int parserEvent = -1;
        XmlPullParser parser = null;
        ArrayList<Employee> items = new ArrayList<Employee>();
        String tag = "";
        Employee item = null;

        try {
            // calls service (referenced in url) to request XML serialized data
            parser = XmlHelper.loadData(url);
            parserEvent = parser.getEventType();

            while (parserEvent != XmlPullParser.END_DOCUMENT) {
                switch(parserEvent) {
                  case XmlPullParser.START_TAG:
                      tag = parser.getName();
                      if (tag.compareTo("Employee") == 0){
                          item = new Employee();
                      }
                  break;
                  case XmlPullParser.END_TAG:
                      tag = parser.getName();
                      if (tag.compareTo("Employee") == 0){
                          items.add(item);
                      }
                  break;
                  case XmlPullParser.TEXT:
                      String text = parser.getText();
                      if (text.trim().length() == 0) break;

                      if (tag.compareTo("Id") == 0){
                          item.Id = Integer.parseInt(text);
                      }
                      else if (tag.compareTo("DeptId") == 0){
                          item.DeptId = Integer.parseInt(text);
                      }
                      else if (tag.compareTo("SalaryGradeId") == 0){
                          item.SalaryGradeId = Integer.parseInt(text);
                      }
                      else if(tag.compareTo("FirstName") == 0){
                          item.FirstName = text;
                      }
                      else if(tag.compareTo("LastName") == 0){
                          item.LastName = text;
                      }
                      else if(tag.compareTo("Email") == 0){
                          item.Email = text;
                      }
                      else if(tag.compareTo("Phone") == 0){
                          item.Phone = text;
                      }
                      else if(tag.compareTo("Title") == 0){
                          item.Title = text;
                      }
                      else if(tag.compareTo("TakesLongLunches") == 0){
                          item.TakesLongLunches = Boolean.parseBoolean(text);
                      }

                  break;
                }

                parserEvent = parser.next();
            }
        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // return de-serialized list of employees
        return items;
    }
}

package com.demo.helpers;

import java.io.*;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

public class XmlHelper {
    public static XmlPullParser loadData(String url) throws XmlPullParserException, IOException
    {
        String xmlData = ResourceHelper.loadManySerialized(url);

        XmlPullParserFactory parserFactory = XmlPullParserFactory.newInstance();
        XmlPullParser parser = parserFactory.newPullParser();
        parser.setInput(new StringReader(xmlData));

        return parser;
    } 
}
To call the EmployeeRepository to obtain an actual list of Employee objects, simply use the following:
ArrayList<Employee> employees = EmployeeRepository.loadMany("http://demos.brianbuikema.com/apps/soa_services/employees?format=XML");

And finally, we’ll deserialize the JSON list.  Please pay special attention as the Employee class has been modified to do its own deserialization/serialization.  I use a static method deserializeArray(…) from within the Employee class, passing it the JSON results from the call toResourceHelper.loadManySerialized(…):
package com.hd.domainmodel;

import java.util.ArrayList;

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

public class Employee {
    public long Id;
    public long DeptId;
    public long SalaryGradeId;
    public String FirstName;
    public String LastName;
    public String Email;
    public String Phone;
    public String Title;
    public boolean TakesLongLunches;

    public Employee() {
    }

    public Employee(JSONObject obj) throws JSONException {
        deserializeFromObj(obj);
    }

    public Employee(String serializedObj) throws JSONException {
        deserialize(serializedObj);
    }

    public void deserialize(String serializedObj) throws JSONException {
        JSONObject obj = new JSONObject(serializedObj);
        deserializeFromObj(obj);
    }

    public void deserializeFromObj(JSONObject obj) throws JSONException {
        this.Id = obj.getLong("Id");
        this.DeptId = obj.getLong("DeptId");
        this.SalaryGradeId = obj.getLong("SalaryGradeId");
        this.FirstName = obj.getString("FirstName");
        this.LastName = obj.getString("LastName");
        this.Email = obj.getString("Email");
        this.Phone = obj.getString("Phone");
        this.Title = obj.getString("Title");
        this.TakesLongLunches = Boolean.parseBoolean(obj.getString("TakesLongLunches"));
    }

    public String serialize() throws JSONException {
        return serializeToObj().toString();
    }

    public JSONObject serializeToObj() throws JSONException {
        JSONObject serializedObj = new JSONObject();
        serializedObj.put("Id", this.Id);
        serializedObj.put("DeptId", this.DeptId);
        serializedObj.put("SalaryGradeId", this.SalaryGradeId);
        serializedObj.put("FirstName", this.FirstName);
        serializedObj.put("LastName", this.LastName);
        serializedObj.put("Email", this.Email);
        serializedObj.put("Phone", this.Phone);
        serializedObj.put("Title", this.Title);
        serializedObj.put("TakesLongLunches", this.TakesLongLunches);

        return serializedObj;
    }

    public static ArrayList<Employee> deserializeArray(String serializedArray) throws JSONException {
        JSONArray jsonObjs = new JSONArray(serializedArray);
        ArrayList<Employee> employees = new ArrayList<Employee>();
        for (int i=0; i<jsonObjs.length(); i++) {
            JSONObject employee = jsonObjs.getJSONObject(i);
            employees.add(new Employee(employee));
        }

        return employees;
    } 
}
o retrieve a list of employee objects, we’ll call the Employee.deserializeArray(…), passing it the serialized String obtained by calling ResourceHelper.loadManySerialized(…).
ArrayList<Employee> employees = Employee.deserializeArray(ResourceHelper.loadManySerialized("http://demos.brianbuikema.com/apps/soa_services/employees?format=JSON"));
This article comes from Brian Buikema