简体   繁体   English

如何使用 Delphi 和 Mormot 库手动创建 JSON?

[英]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).我想手动生成 JSON 来表示复杂的对象(没有任何 RTTI 等)。

Can this be done using Mormot (and how)?这可以使用 Mormot 来完成吗(以及如何)?

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我找到了 JSON Variant 类型,但该类型似乎无法生成像此处那样的复杂 JSON: 在 Delphi 7 中使用 LKJSON 生成 JSON 数组

Of course I could use lkJSON like but since my project already uses Mormot, I would prefer to use the library already in use.当然,我可以使用 lkJSON 之类的,但由于我的项目已经使用了 Mormot,我更愿意使用已经在使用的库。

There are multiple ways in mORMot to generate any kind of json document. mORMot 中有多种方法可以生成任何类型的 json 文档。

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.这应该适用于 Delphi 7 到 10.4。 Please, find further details in the amazing documentation .请在惊人的文档中找到更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM