RTL.JSONBuilder

From RAD Studio Code Examples

Description

This code snippet shows how to write JSON content using the framework System.JSON.Builders.

Code

The following JSON object contains information about purchase records from a website.

{"Transaction":[ 
  {"id":662713, "firstName":"John", "lastName":"Doe", "price": 2.1, "parent_id": null, validated:true},
  {"id":662714, "firstName":"Anna", "lastName":"Smith", "price": 4.5, "parent_id": null, validated: false}, 
  {"id":662715, "firstName":"Peter", "lastName":"Jones", "price": 3.6, "parent_id": null, validated: true} 
  ]}

This sample illustrates how to write the JSON object provided using System.JSON.Builders. The JSON object created is printed to the console.

uses
  System.SysUtils,
  System.Classes,
  System.JSON.Types,
  System.JSON.Writers,
  System.JSON.Builders;

var
  Builder: TJSONObjectBuilder;
  Writer: TJsonTextWriter;
  StringWriter: TStringWriter;
  StringBuilder: TStringBuilder;

begin
  StringBuilder := TStringBuilder.Create;
  StringWriter := TStringWriter.Create(StringBuilder);
  Writer := TJsonTextWriter.Create(StringWriter);
  Writer.Formatting := TJsonFormatting.Indented;
  Builder := TJSONObjectBuilder.Create(Writer);

  Builder
    .BeginObject
      .BeginArray('Transaction')
        .BeginObject.Add('id', 662713)
          .Add('firstName', 'John')
          .Add('lastName', 'Doe')
          .Add('price', 2.1)
          .AddNull('parent_id')
          .Add('validated', true)
        .EndObject
        .BeginObject
          .Add('id', 662714)
          .Add('firstName', 'Anna')
          .Add('lastName', 'Smith')
          .Add('price', 4.5)
          .AddNull('parent_id')
          .Add('validated', false)
        .EndObject
        .BeginObject
          .Add('id', 662715)
          .Add('firstName', 'Peter')
          .Add('lastName', 'Jones')
          .Add('price', 3.6)
          .AddNull('parent_id')
          .Add('validated', true)
        .EndObject
      .EndArray
    .EndObject;
  
  WriteLn(StringBuilder.ToString);

This is the JSON content from the console:

{
  "Transaction": [
    {
      "id": 662713,
      "firstName": "John",
      "lastName": "Doe",
      "price": 2.1,
      "parent_id": null,
      "validated": true
    },
    {
      "id": 662714,
      "firstName": "Anna",
      "lastName": "Smith",
      "price": 4.5,
      "parent_id": null,
      "validated": false
    },
    {
      "id": 662715,
      "firstName": "Peter",
      "lastName": "Jones",
      "price": 3.6,
      "parent_id": null,
      "validated": true
    }
  ]
}

Uses

See Also