Categories
Delphi

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:

{
"PhoneSettings":{
"IP":"192.168.1.100",
"Username":"admin",
"Password":"admin",
"PhoneType":"Snom 300"
},
"Users":[
{
"DisplayName":"User 1",
"Account":"101",
"Password":"101",
"Registrar":"your.voip.provider"
},
{
"DisplayName":"User 2",
"Account":"102",
"Password":"1234",
"Registrar":"your.voip.provider"
},
{
"DisplayName":"User 3",
"Account":"101",
"Password":"101",
"Registrar":"your.voip.provider"
}
]
}

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 );

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.