Javascript Object Notation (JSON) is a lightweight protocol for data interchange that reduces many of the complexities involved in using XML. For more information on JSON, please refer to the [1] JSON website. Morfik 3 has switched from using XML for internal web services to JSON.

Morfik 3 offers support for JSON on both the Browser and Server sides and in debugging through JSON tracing. For the browser and server code refer to the appropriate SystemJSON module.

A Brief Introduction to JSON

A JSON object is basically a collection of name-value pairs where the name is a string that occurs first, followed by a colon (:) followed by a basic type. Available basic types are number, string, boolean, array, JSON object and null. To specify a JSON object it is enclosed in braces ({}), strings are enclosed in double quotes ("") and arrays are enclosed in brackets ([]). Figure 1 is a sample of a Contact JSON object.

{
     "firstName": "Bob",
     "lastName": "Robbin",
     "sex": "M",
     "age": 42,
     "address": 
     {
         "street1": "555 5th Street",
         "street2": '',
         "city": "Golden",
         "state": "CO",
         "zipCode": "80403"
     },
     "phoneNumbers": 
     [
         {
           "type": "home",
           "number": "303 555-1212"
         },
         {
           "type": "cell",
           "number": "303 555-2121"
         }
     ]
 }


Figure 1 JSON Contact Object

Morfik Browser Support for JSON

The browser module SystemJSON declares a variable JSON of type TJSON that includes two important methods: stringify and parse. The stringify methods are used to convert an object to JSON text and the parse methods perform the function in the opposite direction by converting JSON text into an object.

Since JSON support is implemented directly in the browser and does not rely on external dll's, JSON processing is much faster than XML processing and support for JSON on the browser side is guaranteed.

The code sample below demonstrates using these two methods for a new TClient class:

Implementation
 
Uses SystemJSON;
 
Type
    TClient = Class
        Public
            FirstName:   String;
            LastName:    String;
            FavoriteGroup: String;
    End;
 
Procedure Form1.Button1Click(Event: TDOMEvent);
Var
    Str:      String;
    AClient:  TClient;
    BClient:  TClient;
Begin
    AClient := TClient.Create;
    AClient.FirstName := 'Billy Bob';
    AClient.LastName := 'Smith';
    AClient.FavoriteGroup := 'Smashing Pumpkins';
    Str := JSON.Stringify(AClient);
    TextLabel1.Caption := Str;
    BClient := TClient(JSON.parse(Str));        // Creates a new TClient
    TextLabel2.Caption := BClient.FirstName;
End;



Executing a click on Button1 would result in the caption of TextLabel1 being set to {"zb":"tclient","firstname":"Billy Bob","lastname":"Smith","favoritegroup":"Smashing Pumpkins"} and TextLabel2's caption to Billy Bob.

Notice that the result of JSON.stringify includes the additional pair of values "zb":"tclient". This is result of Morfik automatically adding some extra data pairs for the class name to any TObject descendant during the JSON.stringify method (an ancestor class name would also be added when appropriate). Additionally more data pairs will be added for any included methods defined.

To avoid the extra data pairs when creating a string using the stringify method, use TJObject as the ancestor class or a class derived from the TJObject class (TJObject descendants may not include methods).

Simply changing the inheritance in the code above changes the output displayed in TextLabel1.Caption to {"firstname":"Billy Bob","lastname":"Smith","favoritegroup":"Smashing Pumpkins"}. Refer to the code snippets below.


Implementation
 
Uses SystemJSON;
 
Type
    TClient = Class(TJObject)
        Public
            FirstName:   String;
            LastName:    String;
            FavoriteGroup: String;
    End;

Overloaded JSON methods

The JSON.parse method, in addition to the input string parameter can be passed a Reviver parameter which is a function that can be used during the parse method. For a discussion of the reviver parameter refer to http://www.json.org/js.html.

Also, calls to the JSON.stringify method can include a second parameter called a Replacer that would be used to modify the result returned by the stringify method. For a discussion of the Replacer parameter please refer to https://developer.mozilla.org/En/Using_JSON_in_Firefox,Reviver parameters.

Morfik Server Support for JSON

The server module SystemJSON defines a number of classes to support JSON processing, including the JSON class which provides two methods, stringify and parse, that implement the same functionality as the browser side methods. Since both methods are class methods, they can be used without having to create a JSON object on the server.

Along with the JSON class, the server module provide two additional classes, TJSONObject and TJSONList, that provide additional support for JSON, especially to support database objects.

The code below demonstrates using JSON classes on the server-side. The Result from both functions is the string [{"Name":"Bob","Email":"bob@mail.com"},{"Name":"Harry","Email":"harry@mail.com"}] .

Unit Module1;
 
Interface
 
Uses SystemJSON;
 
Function JSONStringifyExample: String;
Function JSONParseExample: String;
 
Implementation
 
Function JSONStringifyExample: String;
Var
  Customer1 : TJSONObject;
  Customer2 : TJSONObject;
  Customers : TJSONList;
 Begin
    Customers := TJSONList.Create;
 
    Customer1 := TJSONObject.Create;
    Customer1.Add('Name', 'Bob');
    Customer1.Add('Email', 'bob@mail.com');
    Customers.Add(Customer1);
 
    Customer2 := TJSONObject.Create;
    Customer2.Add('Name', 'Harry');
    Customer2.Add('Email', 'harry@mail.com');
    Customers.Add(Customer2);
 
    Result := JSON.Stringify(TJSONObject(Customers));
End;
 
Function JSONParseExample: String;
Var
    Customer1 : TJSONObject;
    Customer2 : TJSONObject;
    Customers : TJSONList;
Begin
    Customers := TJSONList.Create;
 
    Customer1 := TJSONObject.Create;
    Customer1 := JSON.Parse('{"Name":"Bob","Status":"Admin"}'); //parsing of a JSON string to JSONObject
    Customers.Add(Customer1);
 
    Customer2 := TJSONObject.Create;
    Customer2 := JSON.Parse('{"Name":"Harry","Status":"User"}');
    Customers.Add(Customer2);                          // adding created and filled object Customer2 to Customers : TJSONList
 
    Result := JSON.Stringify(TJSONObject(Customers));  // Using stringify to see TJSONList
End;
 
End.

Debugging Support

Within Morfik Options, on the Trace panel, JSON object tracing can be turned on by checking the box Monitor JSON Messages. JSON messages will then be displayed at the bottom of the Morfik IDE in the JSON Messages Panel.

Figure 2 below shows sample output from a web method wmTestJSON that adds two integers, Number1 and Number2 and returns the result in an integer Sum.

JSON_Tracing.png
Figure 2: Tracing JSON Messages


Related Topics


Back to top