TDocVariant CRUD Operations

This is based on and the corresponding forum


A TDocVariant custom variant type is declared as a Variant:

 LDocVariant : Variant;

The TDocVariant can be created as an object or from a JSON string. You can use the _Obj/_ObjFast, _JSON/_JSONFast and _Arr/_ArrFast methods to create the TDocVariant.

LDocVariant := _ObjFast( [ 'name', 'bernd' ] );
LDocVariant := _JsonFast( '{ "Person": { "First" : { "name" : "bernd" } } }' );
LDocVariant := _ArrFast( [ _ObjFast( [ 'name', 'bernd' ] ),
                           _ObjFast( [ 'name', 'bob' ] ) ] );


You can access items in the TDocVariant variable dynamically:

Writeln( );
Writeln( LDocVariant.Person.First.Name )
Writeln( LDocVariant._(0).name );

Each of these will output “bernd”.

A TDocVariant will also be cast as JSON string when used in place of a string, for example, using the examples above, calling the following on each respectively:

Writeln( LDocVariant );

will output the following:


For arrays you also have _Count so you can iterate through the array:

for LIndex := 0 to LDocVariant._Count - 1 do
  Writeln( LDocVariant._(LIndex).name );


Updating items and properties is really easy: := "Bernd"; := "Bernd";
LDocVariant._(1).name := "Bob";

You can add objects, array items or values to existing items as well.

LDocVariant.age := 31;
LDocVariant.Person.Next := _ObjFast( ['name','bob'] );
LDocVariant.Person.Next.age = 43;
LDocVariant.Add( _ObjFast( [ 'name', 'ned' ] ) );


All TDocVariant variables have the Delete method to remove an item from the object or array:

LDocVariant.Delete( 'name' );
LDocVariant.Person.Delete( 'Next' );
LDocVariant.Delete( 1 );



Using TDocVariant for settings

Arnaud from Synopse has just released a great new addition to the mORMot framework. TDocVariant is custom variant type which integrates effortless with JSON.

One area that this can be implemented is for the settings of an application. Usually an INI file is the easiest way to implement settings for an application, especially when it is a small utility. INI files mean that you can quickly edit the settings without needing a special editor. Unfortunately arrays, lists and collections are difficult to store in INI files without some sort of pre-determined structure.

JSON eliminates this problem, and allows a truly flexible structure. Now you can use the TDocVariant class to easily read and write the settings as well as access them in your application.

For the snomSwitcher application, the settings are stored in the following format:

"PhoneType":"Snom 300"
"DisplayName":"User 1",
"DisplayName":"User 2",
"DisplayName":"User 3",

We can load the the settings from file by calling:

FSettings := _JsonFast(  StringFromFile( FSettingsFilename ) );

We can then access the settings easily from anywhere in code:

Writeln( FSettings.PhoneSettings.IP );
Writeln( FSettings.Users._(1).Username );