Chapter 9. JSON on the Server Side

When we talk about web client–server relationships, we can categorize technologies as client side or server side:

  • On the client side, we have HTML, CSS, and JavaScript.
  • On the server side, there is PHP, ASP.NET, Node.js, Ruby on Rails, Java, Go, and many, many more.

As a web client, we send requests for resources to a server using HTTP. The server responds with a document, such as HTML or JSON. When that document is a JSON document, the server side code must handle the creation of it.

In addition to serving a JSON document, a server may receive a JSON document. We saw this in Chapter 8 when we used HTTP to post a JSON document to the CouchDB web API. When a document is received, the server-side code must handle the parsing of that document.

In previous chapters, we discussed how JavaScript can make behind-the-scenes HTTP requests for JSON resources to web APIs. It’s easy to think of JavaScript playing this role because it is categorized as “client side.” However, JavaScript isn’t the only language that can make HTTP requests for JSON resources. HTTP requests can also be made by a server-side web framework.

In the scenario where JSON is requested by a server-side technology, its role becomes the client. Here are some example scenarios where HTTP requests are made by server-side web framework code:

  • Using a web API for data to populate dynamic pages of a website. This could be a public third-party web API or your own private web API such as CouchDB.
  • Integrating a payment gateway into checkout code for an ecommerce website by communicating with a web API.
  • Using a web API for retrieving real-time shipping costs for shipping to a specific address.

In this chapter, we will be examining JSON’s role on the server side. A server-side web framework or scripting language produces dynamic web pages. When a request is made for a resource, the server creates the resource with some programming logic.

Serializing, Deserializing, and Requesting JSON

The success of a data interchange format on the Web requires support on both the client and server side. If we were to have support on the client side, but not the server side, JSON would be dead in the water. Fortunately, JSON is widely supported by most server-side web frameworks or scripting languages. If they do not have built-in support for serializing and deserializing JSON, it is likely that a library or extension exists to support it.

Note

As you’ll recall from Chapter 6, serialization is the act of converting the object into text. Deserialization is the act of converting the text back into an object.

Let’s take a look how JSON can be serialized, deserialized, and requested server side.

ASP.NET

ASP.NET is a server-side web framework developed by Microsoft. Originally, web development with this framework was achieved solely with Web Forms, a GUI state-driven model. However, it now includes several extensions that allow for development with different models, such as ASP.NET MVC (a model-view-controller architecture), and ASP.NET web API (an architecture for building HTTP web APIs for Web Services).

Additionally, ASP.NET uses Common Language Runtime (CLR), which allows developers to write their code in any CLR-supported language such as C#, F#, Visual Basic .NET (VB.NET), and many more. In this section, I will be writing all examples in C#.

Unlike JavaScript, ASP.NET does not easily parse JSON. To parse JSON, we must choose a third-party ASP.NET library and bring it into our project. At the time this book is written, the most popular library is Json.NET, an open source JSON framework by Newtonsoft.

Let’s take a look at how we can serialize and deserialize JSON with the Json.NET library.

Serializing JSON

With ASP.NET and Json.NET, we can quickly serialize our ASP.NET objects into JSON. First, I need an object to work with. For this example, we will create an account object with the same structure that we used in Chapter 8 (see Example 9-1).

Example 9-1. A CustomerAccount object in ASP.NET C#
public class CustomerAccount
{
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string phone { get; set; }
    public Address[] addresses { get; set; }
    public bool famous { get; set; }
}

public class Address
{
    public string street { get; set; }
    public string city { get; set; }
    public string state { get; set; }
    public int zip { get; set; }
}

Now that we have a class representing our object, let’s create a new object, for Bob Barker’s account. On the very last line, we will serialize this object to JSON using the Json.NET library (see Examples 9-2 and 9-3).

Example 9-2. A new object for Bob Barker’s account in C#; in the last line, we serialize this object to JSON
CustomerAccount bobsAccount = new CustomerAccount();
bobsAccount.firstName = "Bob";
bobsAccount.lastName = "Barker";
bobsAccount.phone = "555-555-5555";

Address[] addresses;
addresses = new Address[2];

Address bobsAddress1 = new Address();
bobsAddress1.state = "123 fakey st";
bobsAddress1.city = "Somewhere";
bobsAddress1.state = "CA";
bobsAddress1.zip = 96520;

addresses[0] = bobsAddress1;

Address bobsAddress2 = new Address();
bobsAddress2.state = "456 fake dr";
bobsAddress2.city = "Some Place";
bobsAddress2.state = "CA";
bobsAddress2.zip = 96538;

addresses[1] = bobsAddress2;

bobsAccount.addresses = addresses;
bobsAccount.famous = true;

string json = JsonConvert.SerializeObject(bobsAccount);
Example 9-3. The resulting JSON from the serialization of the ASP.NET CustomerAccount object
{
    "firstName": "Bob",
    "lastName": "Barker",
    "phone": "555-555-5555",
    "addresses": [
        {
            "street": null,
            "city": "Somewhere",
            "state": "CA",
            "zip": 96520
        },
        {
            "street": null,
            "city": "Some Place",
            "state": "CA",
            "zip": 96538
        }
    ],
    "famous": true
}

Deserializing JSON

We can deserialize JSON back into an ASP.NET object with one line of code (Example 9-4).

Example 9-4. The deserialization of the JSON string from the earlier example; it is deserialized to the specified type, “CustomerAccount”
CustomerAccount customerAccount = 
    JsonConvert.DeserializeObject<CustomerAccount>(json);

Json.NET gives us the ability to deserialize our JSON into a specific type of object, such as the CustomerAccount object from the example. With this, our data can retain its shape as it moves in and out of the server-side code. However, it is important that our object property names match up with the names of the name-value pairs in our JSON document. Otherwise, deserialization will fail.

Requesting JSON

To make an HTTP request for a resource, I can use the built-in ASP.NET System.Net.WebClient class. With this class, I can call the DownloadString method to download the requested resource from a specified URL as a string (see Examples 9-5 and 9-6).

Example 9-5. Downloading a JSON address document as a string from my local CouchDB addresses database
using(var webClient = new WebClient())
{
    string json = webClient.DownloadString("3636fa3c716f9dd4f7407bd6f700076c");
}
Example 9-6. The JSON resource at the URL http://localhost:5984/accounts/3636fa3c716f9dd4f7407bd6f700076c
{
    "_id": "3636fa3c716f9dd4f7407bd6f700076c",
    "_rev": "2-e04207c11104e06b3a8f030f14c35580",
    "address": {
        "street": "456 Fakey Fake st",
        "city": "Somewhere",
        "state": "CA",
        "zip": "96520"
    },
    "age": 54,
    "gender": "female",
    "famous": true,
    "firstName": "Janet",
    "lastName": "Jackson"
}

Once we have our JSON resource as a string, we can then deserialize it into a desired ASP.NET object using the Json.NET DeserializeObject method (Example 9-7).

Example 9-7. Deserialization of the JSON resource as a string; the fullName variable in the last line of code will evaluate to “Janet Jackson”
CustomerAccount customerAccount;
using (var webClient = new WebClient())
{
    string json = webClient.DownloadString(
        "http://localhost:5984/accounts/3636fa3c716f9dd4f7407bd6f700076c");
    customerAccount = JsonConvert.DeserializeObject<CustomerAccount>(json);              
}

string fullName = customerAccount.firstName + " " + customerAccount.lastName;

In these examples, we can see that the structure of the JSON object makes it friendly for ASP.NET objects. So long as the properties of the ASP.NET object and the names of the name-value pairs of the JSON match up, serializing and deserializing JSON in this web framework is simple.

PHP

PHP is a server-side scripting language used to make dynamic web pages. The PHP code can be embedded directly into HTML documents (see Example 9-8).

Example 9-8. This HTML page will display a header (<h1>) tag with the text “Hello, World”
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Hello, World</title>
    </head>
    <body>
        <h1>
        <?php
           echo "Hello, World";
        ?>
        </h1>
    </body>
</html>

Additionally, PHP includes the object data type. Objects are defined with a class (see Example 9-9).

Example 9-9. A PHP class representing a cat
class Cat
{
    public $name;
    public $breed;
    public $age;
    public $declawed;
}

When a class is instantiated, an object is created. The object can then be used in programming logic (Example 9-10).

Example 9-10. The class is instantiated, and the properties set. An object is created. The last line of code will display “Fluffy Boo.”
   $cat = new Cat();
   $cat->name = "Fluffy Boo";
   $cat->breed = "Maine Coon";
   $cat->age = 2.5;
   $cat->declawed = false;

   echo $cat->name;

PHP also includes built-in support for serializing and deserializing JSON. PHP refers to this as encoding and decoding JSON. When we encode something, we convert it to a coded (unreadable) form. When we decode something, we convert it back into a readable form. From the perspective of PHP, JSON is in a coded format. Therefore, to serialize JSON, the json_encode function is called, and to deserialize JSON, the json_decode function is called.

Serializing JSON

In PHP, we can quickly serialize PHP objects with the built-in support for JSON. In this section, we will create a PHP object representing an address, and serialize to JSON.

In Example 9-11, we first create a class representing an account. Then, we create a new instance of the class for Bob Barker’s account. An Account object is created. Finally, on the last line, we call the built-in function json_encode to serialize the Account object (results shown in Example 9-12).

Example 9-11. Creating and serializing an account
<?php
class Account {
    public $firstName;
    public $lastName;
    public $phone;
    public $gender;
    public $addresses;
    public $famous;
}

class Address {
    public $street;
    public $city;
    public $state;
    public $zip;
}

$address1 = new Address();
$address1->street = "123 fakey st";
$address1->city = "Somewhere";
$address1->state = "CA";
$address1->zip = 96027;

$address2 = new Address();
$address2->street = "456 fake dr";
$address2->city = "Some Place";
$address2->state = "CA";
$address2->zip = 96345;

$account = new Account();
$account->firstName = "Bob";
$account->lastName = "Barker";
$account->gender = "male";
$account->phone = "555-555-5555";
$account->famous = true;        
$account->addresses = array ($address1, $address2);

$json = json_encode($account);

?>
Example 9-12. The JSON result from json_encode($account)
{
    "firstName": "Bob",
    "lastName": "Barker",
    "phone": "555-555-5555",
    "gender": "male",
    "addresses": [
        {
            "street": "123 fakey st",
            "city": "Somewhere",
            "state": "CA",
            "zip": 96027
        },
        {
            "street": "456 fake dr",
            "city": "Some Place",
            "state": "CA",
            "zip": 96345
        }
    ],
    "famous": true
}

Deserializing JSON

To serialize JSON in PHP, we used the built-in json_encode function. To deserialize JSON, we use the json_decode function. Unfortunately, this does not have built-in support for deserializing the JSON to a specified PHP object, such as the Account class. So, we must do a little processing to reshape our data back into the PHP object.

Let’s add a new function to the Account object, to load up its properties from a JSON string.

In Example 9-13, the loadFromJSON function accepts a JSON string for a parameter, calls the built-in json_decode function to deserialize to a generic PHP object, and maps the name-value pairs to the Account properties by name in the foreach loop.

Example 9-13. Adding a function to the Account object
class Account {
    public $firstName;
    public $lastName;
    public $phone;
    public $gender;
    public $addresses;
    public $famous;
    
    public function loadFromJSON($json)
    {
        $object = json_decode($json);
        foreach ($object AS $name => $value) 
        {
            $this->{$name} = $value;
        }
    }
}

Next, we can create a new Account object, and call the new loadFromJSON function (Example 9-14).

Example 9-14. Calling our new loadFromJSON function to deserialize the account JSON back into the Account object; the last line will display “Bob Barker”
$json = json_encode($account);

$deserializedAccount = new Account();
$deserializedAccount->loadFromJSON($json);

echo $deserializedAccount->firstName . " " . $deserializedAccount->lastName;

Requesting JSON

To make an HTTP request for a resource with PHP, I can use the built-in function file_get_contents. This function returns the resource body as a string. We can then deserialize the string to a PHP object (see Examples 9-15 and 9-16).

Example 9-15. Resource at URL http://localhost:5984/accounts/ddc14efcf71396463f53c0f8800019ea from my local CouchDB API
{
    "_id": "ddc14efcf71396463f53c0f8800019ea",
    "_rev": "6-69fd853972074668f99b88a86aa6a083",
    "address": {
        "street": "123 fakey ln",
        "city": "Some Place",
        "state": "CA",
        "zip": "96037"
    },
    "gender": "female",
    "famous": false,
    "age": 28,
    "firstName": "Mary",
    "lastName": "Thomas"
}
Example 9-16. Calling the built-in file_get_contents function to get the account JSON resource from the CouchDB API. Next, a new Account object is created and our loadFromJSON function is called to deserialize. The last line will display “Mary Thomas.”
$url = "http://localhost:5984/accounts/3636fa3c716f9dd4f7407bd6f700076c";
$json = file_get_contents($url);

$deserializedAccount = new Account();
$deserializedAccount->loadFromJSON($json);

echo $deserializedAccount->firstName . " " . $deserializedAccount->lastName;

A Smorgasbord of JSON HTTP Requests

In both the PHP and ASP.NET examples, we can see that though JSON is based on the object literal notation of the JavaScript language, the notation translates well to objects of other programming languages. As server-side programming languages are many and diverse, many of them support objects and the data types of JSON. This is ideal, as it allows the structure or “shape” of the data to be maintained as it moves in and out of a system as JSON.

Additionally, the support for JSON on the server side is massive. Most server-side languages (or frameworks) either provide built-in support for JSON serializing/deserializing, or have libraries or modules available. This support for JSON on the server side contributes to its success as a data interchange format.

Let’s take a look at a few bite-sized examples of JSON HTTP requests on the server side. In each of these examples, you will see an HTTP request for a JSON resource, the parsing of that resource into an object, and the rendering of a value from a JSON document.

The JSON document in all these examples will be from the OpenWeatherMap API. All the rendering of values will be based on a subset of the JSON resource at http://api.openweathermap.org/data/2.5/weather?q=London,uk (see Example 9-17).

Example 9-17. The coordinates object of the JSON resource for weather data from the OpenWeatherMap API; this represents the latitude and longitude of London, UK
{
    "coord": {
        "lon": -0.13,
        "lat": 51.51
    }
}

Ruby on Rails

Ruby on Rails is a server-side web application framework. It is written in the Ruby programming language and based on the model-view-controller (MVC) architecture.

In Ruby, a gem is a package for installing a program or library. To serialize and deserialize JSON in Ruby on Rails, the JSON ruby gem is required. Once you have the JSON gem installed, parsing JSON is as simple as JSON.parse() (Example 9-18).

In Example 9-18, we make an HTTP request to the OpenWeatherMap API and deserialize the JSON into a Ruby Object. Finally, in the last line of the code, we render the longitude (lon) from the coordinates (coord) object of the data.

Example 9-18. HTTP Request to the OpenWeatherMap API
require 'net/http'
require 'json'

url = URI.parse('http://api.openweathermap.org/data/2.5/weather?q=London,uk')
request = Net::HTTP::Get.new(url.to_s)
response = Net::HTTP.start(url.host, url.port) {|http|
http.request(request)
}

weatherData = JSON.parse(response.body)

render text: weatherData["coord"]["lon"]

Node.js

Node.js is JavaScript on the server  side (without an Internet browser), made possible with Google’s open source V8 JavaScript engine. With Node.js, you can build server-side applications with JavaScript.

Earlier in this book, we covered JSON with JavaScript on the client side and saw that JSON is deserialized into a JavaScript object with a simple JSON.parse(). The same is true in Node.js, as it is JavaScript.

However, we don’t use the XMLHttpRequest object in Node.js, as it is a JavaScript object specific to Internet browsers. In Node.js, we can request our JSON (and other types of resources) with a much better named function: get().

In Example 9-19, we make an HTTP request to the OpenWeatherMap API and deserialize the JSON into a JavaScript Object. We then print the longitude (lon) from the coordinates (coord) object of the data with console.log().

Example 9-19. Making an HTTP request to the API and deserializing to a JavaScript object
var http = require('http'),
http.get({
    host: 'api.openweathermap.org',
    path: '/data/2.5/weather?q=London,uk'
}, function(response) {
    var body = '';
    response.on('data', function(data) {
        body += data;
    });
    response.on('end', function() {
        var weatherData = JSON.parse(body);
        console.log(weatherData.coord.lon);
    });
});

Java

Java is an object-oriented programming language. Java can be run in the web browser as Java applets, or standalone on a machine with the Java Runtime Environment (JRE).

There are many libraries available that support JSON in Java. In this section, I will use the following libraries to get the JSON resource from a URL and deserialize it to an object in Java:

In Example 9-20, we get the JSON resource as a string from the OpenWeatherMap API. After that, we deserialize the JSON string by instantiating a JSONObject. We then print the longitude (lon) from the coordinates (coord) object of the data with System.out.println().

Example 9-20. Deserializing a JSON string with a JSONObject
import java.io.IOException;
import java.net.URL;
 
import org.apache.commons.io.IOUtils;
import org.json.JSONException;
import org.json.JSONObject;

public class HelloWorldApp {

    public static void main(String[] args) throws IOException, JSONException {
        String url = "http://api.openweathermap.org/data/2.5/weather?q=London,uk";
        String json = IOUtils.toString(new URL(url));
        JSONObject weatherData = new JSONObject(json);
        JSONObject coordinates = weatherData.getJSONObject("coord");
        System.out.println(coordinates.get("lon"));
    }  
    
}

Key Terms and Concepts

This chapter covered the following key terms:

ASP.NET
A server-side web framework developed by Microsoft.
PHP
A server-side scripting language used to make dynamic web pages.
Ruby on Rails
A server-side web application framework running on Ruby.
Node.js
JavaScript on the server side running on Google’s V8 JavaScript engine.
Java
An object-oriented programming language.

We also discussed these key concepts:

  • On the server side, JSON can be deserialized into an object for use in programming logic and serialized into JSON format from an object.
  • JSON has a huge amount of support on both the client side and the server side, which makes it a very successful data interchange format for the Web.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.170.134