Handling JSON NULL values in Delphi

There is a quite frequent question about how to correctly handle NULL values in Delphi using System.Json.TJSONObject.

Handling existing values, in this example, the array of „customers“ is fairly easy:

{"customers":[{"name":"Olaf"},{"name":"Big Bird"}]}

But what, if the array is „null“?

{"customers":null}
const
CUSTOMERS = '{"customers":[{"name":"Olaf"},{"name":"Big Bird"}]}';
CUSTOMERS_NULL = '{"customers":null}';
procedure TForm39.Button1Click(Sender: TObject);
var
LContainer: TJSONValue;
LCustomers: TJSONArray;
begin
//Here, the value is not nil, so you can just go ahead with GetValue
LContainer := TJSONObject.ParseJSONValue(CUSTOMERS);
try
LCustomers := LContainer.GetValue<TJSONArray>('customers');
Assert(LCustomers.Count = 2);
finally
FreeAndNil(LContainer);
end;
// If the value can be null though, then specify a default - which can be "nil"
LContainer := TJSONObject.ParseJSONValue(CUSTOMERS_NULL);
try
LCustomers := nil;
LCustomers := LContainer.GetValue<TJSONArray>('customers', nil);
Assert(LCustomers = nil);
finally
FreeAndNil(LContainer);
end;
// There is also TryGet, but that's probably slower and less convenient
LContainer := TJSONObject.ParseJSONValue(CUSTOMERS_NULL);
try
LCustomers := nil;
LContainer.TryGetValue('customers', LCustomers);
Assert(LCustomers = nil);
finally
FreeAndNil(LContainer);
end;
view raw test.pas hosted with ❤ by GitHub