jsondelphimormot

How can you create JSON manually using Delphi with the Mormot library?


I would like to generate JSON to represent complex object, manually (without any RTTI etc).

Can this be done using Mormot (and how)?

I have found the JSON Variant type, but that one does not seem to be capable of producing a complex JSON like the one here: Generate JSON array with LKJSON in Delphi 7

Of course I could use lkJSON like but since my project already uses Mormot, I would prefer to use the library already in use.


Solution

  • There are multiple ways in mORMot to generate any kind of json document.

    You can find below one of them serializing the example you provided, IMHO more readable and easy to understand:

    ...
    uses SynCommons;
    ...
    var parcelas , venda , vendas , json : variant;
    begin
      parcelas := _Obj(['numero',1,
                        'valor',50
                       ]);
      venda    := _Obj(['nsuOrigem','1',
                        'data','2014-03-14',
                        'nrParcelas',1,
                        'valor',50,
                        'parcelas' , _Arr([parcelas
                                          ])
                       ]);
      vendas := _Arr([venda]);
      venda := _Obj(['nsuOrigem','2',
                     'data','2014-03-14',
                     'nrParcelas',1,
                     'valor',50,
                     'parcelas' , _Arr([parcelas  //in this case this object is the same
                                       ])
                    ]);
      TDocVariantData(vendas).AddItem(venda);
      json := _Obj(['nrVendas',2,
                    'totalVendas',100.0,
                    'vendas',vendas
                   ]);
      //
      assert(json.nrVendas=2);
      assert(json.vendas._count=2);
      assert(json.vendas._(0).nsuOrigem='1');
      assert(json.vendas._(1).nsuOrigem='2');
      assert(json.vendas._(1).parcelas._(0).valor=50);
    end;
    

    This should work from Delphi 7 to 10.4. Please, find further details in the amazing documentation.