Skip to content

Instantly share code, notes, and snippets.

@omonien
Last active February 1, 2020 22:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omonien/791182338006e777842e90f19bdd7375 to your computer and use it in GitHub Desktop.
Save omonien/791182338006e777842e90f19bdd7375 to your computer and use it in GitHub Desktop.
Handling NULL JSON values in Delphi
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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment