Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Catalog · How the catalog works

Random project

REST-Json-Helpers

Some helpers for serializing objects to JSON and back using the standard Delphi library.

View on GitHub

Anyone may press Interesting, signed in or not. It helps others find this project.

Member rating

No ratings yet.

Sign in to rate this project.

README

REST-JSon-Helpers

The unit provides some helper classes to make serializing classes into JSON a bit easier.

JsonUTCDate

The JsonUTCDate attribute applied to ca field results in the field value being converted into UTC format when serialized into JSON format. Of course the conversion is reverted when the field is set from JSON. If the field value equals cNoDate (i.e. "0000-00-00T00:00:00.000Z") conversion from/into local time format is skipped. When writing such a value it will result in a JSON null object value.

Usage:

delphi
type
  TMyClass = class
  private
    [JsonUTCDate]
    FStartDate: TDateTime;
    [JsonUTCDate]
    FEndDate: TDateTime;
    ...
  end;

JsonStrings

The JsonStrings attribute applied to a TStrings or descendant will serialize the strings to an array of string and vice versa. Note that it should always be accompanied by JSONOwned(False).

Usage:

delphi
type
  TMyClass = class
  private
    [JSONOwned(False), JSONStrings]
    FLines: TStringList;
    ...
  end;

JsonObjectListAttribute<T>

JsonObjectListAttribute<T> is a generic attribute that must be derived to resolve the generic. The derived attribute can then be applied to a TObjectList<T> descendant. It makes the list being serialized to an array of object and back again.

Each field holding such a list requires a JSONOwned(False) attribute to avoid the list instance being destroyed during deserialisation.

Usage:

delphi
type
  TContact = class
    ...
  end;

  JsonObjectListContactAttribute = class(JsonObjectListAttribute<TContact>); { the class keyword is mandatory }
  
type  { this type keyword is mandatory }
  [JsonObjectListContact]
  TContactList = class(TIdentList<TContact>);

type
  TMyAddressBook = class
  private
    [JSONOwned(False)] { this attribute is mandatory to avoid FContacts being destroyed }
    FContacts: TContactList;
    ...

The new attribute (JsonObjectListContactAttribute) as well as the new list (TContactList) must not be an alias - the class keyword is mandatory. Also there must be at least one type keyword between the declaration and the use of the attribute.

Note: The previous version required the declaration of an TObjectListInterceptor<T> descendant, which was given to a non-generic version of the attribute. The new approach is much easier to use.

TConvert

TConvert is a record providing some helpful methods to convert to and from Json. In addition to Json objects it can also produce Json arrays, as well as revert them with its FromJSONArray methods.