Last active
February 1, 2020 22:26
-
-
Save omonien/791182338006e777842e90f19bdd7375 to your computer and use it in GitHub Desktop.
Handling NULL JSON values in Delphi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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