Skip to content

JSON Serialization ​

MARS maps Delphi values to and from JSON through the helpers in MARS.Core.JSON.pas. In day-to-day use you simply return records/objects/arrays and accept them as [BodyParam] — the content-negotiation layer does the rest. This page covers the conversion rules and how to customize them.

What serializes to what ​

Delphi typeJSON
string, Charstring
Integer, Int64, Double, Currencynumber
Booleantrue / false
TDateTime / TTimestring (ISO-8601 by default) or Unix number
TDatestring, the calendar date: "2026-10-19" (OpenAPI format: date; see Dates)
enumstring or number
recordobject (one key per field)
class (TObject)object (published/visible properties)
TArray<T> / TObjectList<T>array
TJSONValuepassed through as-is (a result, a field)
TJSONRawStringthe JSON it contains (see Raw JSON fields)
TDataSet / TFDDataSetarray of objects (see Data Access)

Nested records, arrays of records, and arrays of objects all serialize recursively.

Floating point numbers ​

Double, Single and float fields of datasets are written with the shortest text that reads back to the same value, as JavaScript, Python or Java do: 0.1, 0.30000000000000004 (0.1 + 0.2), 1.2345678901234567, 3.0, 1E-20; a Single with its own digits (0.1, not 0.100000001490116). JSON numbers are read as the nearest Double, a Currency from its text (all its 19 digits). TJSONNumber.Create and AsDouble of the RTL use 15 significant digits and are not correctly rounded: to build or read JSON by hand without losing precision, use DoubleToJSONNumber, SingleToJSONNumber and JSONNumberToFloat (MARS.Core.JSON), or FloatToJSONText and TryJSONTextToFloat (MARS.Utils.FloatText).

Direct conversion helpers ​

When you need to convert explicitly (not through a resource result), use the TJSONObject class helpers:

pascal
uses MARS.Core.JSON;

// record  <->  JSON
var LJson := TJSONObject.RecordToJSON<TPerson>(LPerson, DefaultMARSJSONSerializationOptions);
var LPerson := TJSONObject.JSONToRecord<TPerson>(LJson, DefaultMARSJSONSerializationOptions);

// object  <->  JSON
var LJson := TJSONObject.ObjectToJSON(LCustomer, DefaultMARSJSONSerializationOptions);
var LCustomer := TJSONObject.JSONToObject<TCustomer>(LJson);

// any TValue -> TJSONValue
var LValue := TJSONObject.TValueToJSONValue(TValue.From(LPerson), DefaultMARSJSONSerializationOptions);

When mapping JSON to an object, a member whose key is not in the JSON keeps its current value: defaults set by the constructor survive, sub-objects the constructor created stay in place (a nested JSON object fills them, it does not replace them), and ToObject on an existing instance merges the keys present into it. Declare a _AssignedValues: TArray<string> field to be told which members actually came from the JSON. Members of a record start zeroed, so the same rule applies.

A TObjectList<T> member is read from a JSON array, its elements as T: a list the constructor created is emptied and filled (the same instance), a nil member gets a new list that owns its objects (Create(True)). Either way the object that holds the list frees it in its destructor; a list your constructor creates should own its objects too (Create(True), the default), since the objects MARS reads into it are freed by nobody else. A [BodyParam] of type TObjectList<T> is read from a JSON array the same way (MARS frees it after the method):

pascal
TOrder = class
public
  Number: string;
  Lines: TObjectList<TOrderLine>; // {"Lines": [{...}, {...}]}
  destructor Destroy; override;    // Lines.Free
end;

Serialization options ​

TMARSJSONSerializationOptions controls how empty/null values and dates are emitted. There is a global default you can tune once during ignition:

pascal
uses MARS.Core.JSON;

// Include empty/null values in output...
DefaultMARSJSONSerializationOptions.IncludeEmptyOrNullValues;

// ...or strip them all
DefaultMARSJSONSerializationOptions.SkipAllEmptyOrNullValues;

The fields you can set:

FieldEffect
SkipEmptyStringsOmit "" values.
SkipEmptyNumbersOmit zero numbers.
SkipEmptyBooleansOmit false values.
SkipEmptyObjects / SkipEmptyArraysOmit empty {} / [].
SkipNullValuesOmit null.
DateIsUTCTreat TDateTime as UTC.
ZeroDateAsEmptyWrite a zero date (0, 1899-12-30) as "", "no date" (default True; then omitted by SkipEmptyStrings). False writes it as a date (1899-12-30T00:00:00.000Z).
TDateAsDateWrite TDate values as calendar dates, "2026-10-19" (default True). False writes them as the other dates ("2026-10-19T00:00:00.000+02:00"), as MARS 2.0.2 and earlier.
DateFormatReserved: dates are always written and read as ISO 8601.
UseDisplayFormatForNumericFieldsUse a field's display format for dataset numbers.

The default is "skip most empty/null values, ISO-8601 dates". DateIsUTC defaults to True only when the machine runs at UTC+0; set it explicitly (in code or in the configuration file) to get the same behavior everywhere.

Dates ​

TDateTime (and TTime) values are a moment: ISO 8601 with the time and the offset ("2026-10-19T09:30:00.000+02:00", or Z with DateIsUTC). TDate values are a day of the calendar, the same in every time zone: "2026-10-19", the full-date of RFC 3339 that OpenAPI calls format: date (and the OpenAPI document of the server says so). A time in a TDate (i.e. Now) is left out.

Reading, a TDate accepts "2026-10-19" as that day, and a date with a time (as clients and MARS 2.0.2 and earlier write it) as its day in local time. A TDateTime reads "2026-10-19" as midnight of that day, without converting it between time zones. Path, query and header parameters of type TDate work the same way.

TDateAsDate = False (JSON.TDateAsDate=false) writes TDate values with the time and the offset again, i.e. while clients built with MARS 2.0.2 or earlier still read TDate values of the server as TDateTime (they would read "2026-10-19" as midnight UTC, converted to their local time).

From the configuration file ​

The same options can be set per application with JSON.* parameters, without recompiling:

ini
[DefaultEngine]
; send empty strings too
DefaultApp.JSON.SkipEmptyStrings=false
; keep dates in UTC
DefaultApp.JSON.DateIsUTC=true

JSON.SkipEmptyValues sets all the Skip* options at once; a specific parameter written along with it wins. A value that is not true/false raises an error at the first request that uses it.

Each request combines the options in this order, the last one winning:

  1. the global default, DefaultMARSJSONSerializationOptions (set in code);
  2. the JSON.* parameters of the application;
  3. the attributes of the resource class ([JSONIncludeEmptyValues], [JSONSkipEmptyValues], [JSONDateIsUTC]);
  4. the attributes of the method.

[JSONDateIsUTC] writes and reads the dates of a resource or a method (records, objects, datasets) as UTC ("2026-07-15T09:30:00.000Z"), [JSONDateIsUTC(False)] as local times with their offset ("2026-07-15T09:30:00.000+02:00"), whatever JSON.DateIsUTC says:

pascal
[GET, Path('{id}/events'), JSONDateIsUTC]
function GetEvents: TArray<TEvent>;

They apply to responses (objects, records, arrays, datasets) and to requests: the readers of objects and records use the same options, so dates are read with the DateIsUTC they are written with. MCP dataset results follow them too.

Non-ASCII characters ​

By default the JSON text of a response escapes every character above 127: "Città" is sent as "Citt\u00E0". It is valid JSON and every client decodes it, but it is hard to read while debugging and takes more bytes. Set the JSON.EscapeNonASCII application parameter to false to send the characters as they are:

ini
[DefaultEngine]
DefaultApp.JSON.EscapeNonASCII=false

or change the default for every application in code, during ignition:

pascal
uses MARS.Core.MessageBodyWriters;

TJSONValueWriter.DefaultEscapeNonASCII := False;

Control characters (below 32) are always escaped, as JSON requires. When a resource sets a non-Unicode response encoding with [Encoding], the escapes are kept, so no character is lost. The setting applies to every JSON response written by MARS: objects, records, arrays, datasets.

Per-field control attributes ​

Annotate record/class fields to override the global behavior:

AttributeEffect
[JSONName('customKey')]Serialize the field under a different JSON key.
[JSONSkip]Exclude the field entirely.
[JSONSkipEmptyValues]For this object, omit empty/null members.
[JSONIncludeEmptyValues]For this object, include empty/null members.
pascal
type
  TUser = record
    [JSONName('user_name')] Name: string;
    Email: string;
    [JSONSkip] PasswordHash: string;   // never leaves the server
  end;

[JSONSkipEmptyValues] / [JSONIncludeEmptyValues] can also decorate a resource or method to set the policy for its responses — as the OpenAPI resource does with [JSONSkipEmptyValues].

Custom JSON shapes ​

If you need a response shape that doesn't match a Delphi type one-to-one, you have three options, in increasing order of control:

  1. Build a TJSONObject/TJSONArray yourself and return it (it passes through unchanged).
  2. Register a custom MessageBodyWriter for your type.
  3. Return a TMARSResponse and write the body directly.
pascal
[GET, Produces(TMediaType.APPLICATION_JSON)]
function Summary: TJSONObject;
begin
  Result := TJSONObject.Create;
  Result.AddPair('count', TJSONNumber.Create(ComputeCount));
  Result.AddPair('generatedAt', DateToISO8601(Now));
end;

Raw JSON fields ​

A field that holds any JSON value (an object of unknown shape, a value that can be a string or a number) can be declared as:

  • TJSONRawString (MARS.Core.JSON): the JSON as text. It is read from any value ({"a":1}, [1,2], "text" with its quotes, 42, true; null gives an empty string) and written back as JSON, not as a string. An empty value is null, so the JSON.SkipNullValues option applies; text that is not valid JSON is written as a string. In a record this is the simplest choice: nothing to free.
  • TJSONValue (or TJSONObject, TJSONArray): a copy of the value, written as JSON. The copy belongs to whoever reads the record or object, which must free it; a TJSONObject or TJSONArray field accepts only that kind of value.
pascal
TEvent = record
  Name: string;
  Payload: TJSONRawString;  // {"Name":"saved","Payload":{"id":7,"tags":["a"]}}
end;

YAML ​

With MARS.YAML.ReadersAndWriters in your ignition uses, methods that [Produces(TMediaType.APPLICATION_YAML)] can emit YAML for the same record/object types — this is how the OpenAPI endpoint serves both JSON and YAML from one method.

YAML uses libyaml through the bundled Neslib.Yaml, which is available on Windows (32 and 64 bit), Android, iOS and 32-bit macOS. Source\MARS.inc defines MARS_YAML on those platforms only; guard the unit in your uses with it, as the templates do:

pascal
{$IFDEF MARS_YAML}
, MARS.YAML.ReadersAndWriters
{$ENDIF}

On Linux and 64-bit macOS (OSX64, OSXARM64) the unit compiles empty and registers no writer: a method that produces JSON and YAML answers in JSON (no Accept, */* or application/json), while a request that accepts only application/x-yaml gets 406 Not Acceptable (see When no writer matches).

YAML follows the same serialization options as JSON, for the same request: the global default, then the JSON.* parameters of the application, then the attributes of the resource and of the method. Dates are written as in JSON (DateIsUTC, ZeroDateAsEmpty, TDateAsDate), and the SkipEmpty* options decide which empty members are left out (an empty array is [], an empty object {}); the elements of a sequence are always written, to keep their position. There are no YAML.* parameters; JSON.EscapeNonASCII and UseDisplayFormatForNumericFields apply to JSON only. TMARSYAML (ObjectToYAML, RecordToYAML, TValueToYAML) takes the options as AOptions; without them it uses DefaultMARSJSONSerializationOptions.

Released under the Mozilla Public License 2.0.