如何正确地将非字符串值添加到 TJSONObject?

Fab*_*zio 7 delphi json

使用 a TJSONObject,我注意到它的AddPair函数有以下重载:

function AddPair(const Pair: TJSONPair): TJSONObject; overload;
function AddPair(const Str: TJSONString; const Val: TJSONValue): TJSONObject; overload;
function AddPair(const Str: string; const Val: TJSONValue): TJSONObject; overload;
function AddPair(const Str: string; const Val: string): TJSONObject; overload;
Run Code Online (Sandbox Code Playgroud)

特别是,我注意到添加非字符串值(如整数、日期时间)没有重载......由于这个原因,调用ToString函数时,每个值都显示为双引号:

{"MyIntegerValue":"100"}

从我在这个答案中读到的内容来看,它违反了非字符串值的 JSON 标准。如何将非字符串值添加到 a 中TJSONObject

Seb*_*ske 13

您可以使用TJSONNumber和用于创建数字 JSON 值的AddPair重载TJSONValue,如下所示:

program Project1;

{$APPTYPE CONSOLE}

uses
  System.SysUtils, System.JSON;

var
  JSON: TJSONObject;
begin
  JSON := TJSONObject.Create;
  try
    JSON.AddPair('MyIntegerValue', TJSONNumber.Create(100));
    writeln(JSON.ToString);
    readln;
  finally
    JSON.Free;
  end;
end.
Run Code Online (Sandbox Code Playgroud)

输出 {"MyIntegerValue":100}

这也是它在help中的代码示例中的完成方式。