7

Using a TJSONObject, I've noticed that its AddPair function has the following overloads:

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;

In particular, I've noticed that there's no overload for adding not-string values like integers, datetimes... Due to this reason, calling ToString function, every value is shown as double quoted:

{"MyIntegerValue":"100"}

From what I've read in this answer, it goes against the JSON standard for not-string values. How should a not-string value be added to a TJSONObject?

Community
  • 1
  • 1
Fabrizio
  • 7,603
  • 6
  • 44
  • 104

1 Answers1

13

You can use TJSONNumber and the AddPair overload that uses TJSONValue to create a numeric JSON value, like so:

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.

Outputs {"MyIntegerValue":100}

This is also how it's done in the codesample from help.

Sebastian Proske
  • 8,255
  • 2
  • 28
  • 37
  • 1
    This answer is technically correct. I would add that, at least on desktop platforms, the `TJSONNumber` object should be protected by a `try/except` block to free the object if `AddPair()` raises an exception, like a memory error (it is rare, but still possible), otherwise the object will be leaked. `number := TJSONNumber.Create(100)); try JSON.AddPair('MyIntegerValue', number); except number.Free; raise; end;` On mobile platforms, this is not needed since ARC will handle everything for you. – Remy Lebeau Feb 10 '17 at 21:45