Book Image

Delphi Cookbook

By : Daniele Teti
Book Image

Delphi Cookbook

By: Daniele Teti

Overview of this book

Table of Contents (14 chapters)
Delphi Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Manipulating JSON


JavaScript Object Notation (JSON) is a lightweight data-interchange format. As the reference site (http://www.json.org) says:

It is easy for humans to read and write. It is easy for machines to parse and generate.

It is based on a subset of the JavaScript programming language, but it is not limited to JavaScript in any way. Indeed, JSON is a text format that is completely language agnostic. These properties make JSON an ideal data-interchange language for many utilizations. In recent years, JSON has superseded XML in many applications, especially on data exchange and in general when the data size matters, because of its intrinsic conciseness and simplicity.

Getting ready

JSON provides the following five datatypes: string, number, object, array, Boolean, and null.

This simplicity is a plus when you have to read a JSON string into some kind of language-specific structures, because every modern language supports JSON datatypes as simple types, HashMap (in case of JSON object), or List (in case of JSON array). So, it makes sense that a data format that is interchangeable with programming languages is also based on these types and structures.

Since Version 2009, Delphi provides built-in support for JSON. The System.JSON.pas unit contains all JSON types with a nice object-oriented interface. In this recipe, we'll see how to generate, modify, and parse a JSON string.

How to do it…

  1. Create a new VCL application and drop three TButton and a TMemo. Align all the buttons as a toolbar at the top of the form and the memo to all the remaining form client area.

  2. From left- to right-hand side, name the buttons as btnGenerateJSON, btnModifyJSON, and btnParseJSON.

  3. We'll use static data as our data source. A simple matrix is enough for this recipe. Just after the start of the implementation section of the unit, write the following code:

    type
      TCarInfo = (
       Manufacturer = 1, 
       Name = 2, 
       Currency = 3, 
       Price = 4);
    
    var
      Cars: array [1 .. 4] of 
             array [Manufacturer .. Price] of string = (
              ('Ferrari','360 Modena','EUR', '250000'),
              ('Ford', 'Mustang', 'USD', '80000'),
              ('Lamborghini', 'Countach', 'EUR','300000'),
              ('Chevrolet', 'Corvette', 'USD', '100000')
              ); 
  4. The TMemo component is used to show our JSON and our data. To keep things clear, create on the form a public property called JSON and map its setter and getter to the Memo1.Lines.Text property. Use the following code for this:

    //…other form methods declaration 
    private
      procedure SetJSON(const Value: String);
      function GetJSON: String;
    public
      property JSON: String read GetJSON write SetJSON;
    end;
    
    //…then in the implementation section
    function TMainForm.GetJSON: String;
    begin
      Result := Memo1.Lines.Text;
    end;
    
    procedure TMainForm.SetJSON(const Value: String);
    begin
      Memo1.Lines.Text := Value;
    end;
    
  5. Now, create event handlers for each button and write the following code. Pay attention to the event names. The code is as follows:

    procedure TMainForm.btnGenerateJSONClick(Sender: TObject);
    var
      i: Integer;
      JSONCars: TJSONArray;
      Car, Price: TJSONObject;
    begin
      JSONCars := TJSONArray.Create;
      try
        for i := Low(Cars) to High(Cars) do
        begin
          Car := TJSONObject.Create;
          JSONCars.AddElement(Car);
          Car.AddPair('manufacturer', 
              Cars[i][TCarInfo.Manufacturer]);
          Car.AddPair('name', Cars[i][TCarInfo.Name]);
          Price := TJSONObject.Create;
          Car.AddPair('price', Price);
          Price.AddPair('value', 
             TJSONNumber.Create(
                   Cars[i][TCarInfo.Price].ToInteger));
          Price.AddPair('currency', 
             Cars[i][TCarInfo.Currency]);
        end;
        JSON := JSONCars.ToString;
      finally
        JSONCars.Free;
      end;
    end;
    
    procedure TMainForm.btnModifyJSONClick(Sender: TObject);
    var
      JSONCars: TJSONArray;
      Car, Price: TJSONObject;
    begin
      JSONCars := TJSONObject.ParseJSONValue(JSON) 
                          as TJSONArray;
      try
        Car := TJSONObject.Create;
        JSONCars.AddElement(Car);
        Car.AddPair('manufacturer', 'Hennessey');
        Car.AddPair('name', 'Venom GT');
        Price := TJSONObject.Create;
        Car.AddPair('price', Price);
        Price.AddPair('value', TJSONNumber.Create(600000));
        Price.AddPair('currency', 'USD');
        JSON := JSONCars.ToString;
      finally
        JSONCars.Free;
      end;
    end;
    
    procedure TMainForm.btnParseJSONClick(Sender: TObject);
    var
      JSONCars: TJSONArray;
      i: Integer;
      Car, JSONPrice: TJSONObject;
      CarPrice: Double;
      s, CarName, CarManufacturer, CarCurrencyType: string;
    begin
      s := '';
      JSONCars := TJSONObject.ParseJSONValue(JSON) 
             as TJSONArray;
      if not Assigned(JSONCars) then
        raise Exception.Create('Not a valid JSON');
      try
        for i := 0 to JSONCars.Size - 1 do
        begin
          Car := JSONCars.Get(i) as TJSONObject;
          CarName := Car.Get('name').JsonValue.Value;
          CarManufacturer := Car.Get('manufacturer')
             .JsonValue.Value;
          JSONPrice := Car.Get('price')
             .JsonValue as TJSONObject;
          CarPrice := (JSONPrice.Get('value').JsonValue 
                          as TJSONNumber).AsDouble;
          CarCurrencyType := JSONPrice.Get('currency')
                                .JsonValue.Value;
          s := s + Format(
            'Name = %s' + sLineBreak +
            'Manufacturer = %s' + sLineBreak +
            'Price = %.0n%s' + sLineBreak +
            '-----' + sLineBreak, 
          [CarName, CarManufacturer, 
          CarPrice, CarCurrencyType]);
        end;
        JSON := s;
      finally
        JSONCars.Free;
      end;
    end;
    
  6. Run the application by hitting F9 (or navigate to Run | Run).

  7. Click on the btnGenerateJSON button, and you should see a JSON array and some JSON objects inside in the memo.

  8. Click on the btnModifyJSON button and you should see one more JSON object inside the outer JSON array in the memo.

  9. Click on the last button and you should see the same data as before, but in a normal text representation.

  10. After the third click, you should see something like the following screenshot:

    Text representation of the JSON data generated and modified

There's more...

Although not the fastest or the most standard compliant on the market (at the time of writing), it is important to know the JSON Delphi parser because other Delphi technologies such as DataSnap use it. Luckily, there are a lot of alternative JSON parsers for Delphi if you find you have trouble with the standard ones.

Other notable JSON parsers are as follows:

If your main concern is speed, then check the Delphi Web Script or the superobject parsers.

There are also a lot of serialization libraries that use JSON as a serialization format. In general, every parser has its own way to serialize an object to JSON. Find your favorite. For example, in the Serializing objects to JSON and back using RTTI recipe in Chapter 5, Putting Delphi on the Server, you will see an open source library containing a set of serialization helpers using the default Delphi JSON parser.

However, JSON is not the right tool for every interchange or data representation job. XML has been creating other technologies that can help if you need to search, transform, and validate your data in a declarative way. In JSON land, there is no such level of standardization apart from the format itself. However, over the years, there is an effort to include at least the XML Schema counterpart in JSON, and you can find more details at http://json-schema.org/.