Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly add not-string values to a TJSONObject?

Tags:

json

delphi

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?

like image 501
Fabrizio Avatar asked Feb 10 '17 14:02

Fabrizio


1 Answers

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.

like image 97
Sebastian Proske Avatar answered Oct 16 '22 22:10

Sebastian Proske