• TDocVariant CRUD Operations

    This is based on http://blog.synopse.info/post/2014/02/25/TDocVariant-custom-variant-type and the corresponding forum http://synopse.info/forum/viewtopic.php?id=1631


    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( LDocVariant.name );
    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:

    LDocVariant.name := "Bernd";
    LDocVariant.Person.First.name := "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 );


Leave a comment

If you want to share your opinion, leave a comment.

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

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