Which JSON method is better practice to use: Get() or GetValue()?

181 Views Asked by At

Given the following two lines of code produce the same output, which of the two methods is better practice?

TJSONArray *resultsArray = (TJSONArray*) response->Get("results")->JsonValue;

TJSONArray *resultsArray = (TJSONArray*) response->GetValue("results");
1

There are 1 best solutions below

0
Remy Lebeau On BEST ANSWER

GetValue() is functionally the same as calling Get()->JsonValue, but with an extra check to make sure the requested key actually exists before accessing its JsonValue.

TJSONObject has a protected GetPairByName() method, which returns a pointer to the TJSONPair object of the requested key if found, or NULL if the key is not found.

Get() simply calls GetPairByName() and returns the pointer as-is:

function TJSONObject.Get(const Name: string): TJSONPair;
begin
  Result := GetPairByName(Name);
end;

If you know for sure that the key exists, using Get()->JsonValue is perfectly safe. But, if there is any possibility that the key may not exist, you need to check the return value for NULL before accessing any of the TJSONPair's members.

GetValue() calls GetPairByName() and returns the JsonValue of the returned TJSONPair only if the key is found, otherwise it returns NULL:

function TJSONObject.GetValue(const Name: string): TJSONValue;
var
  LPair: TJSONPair;
begin
  LPair := GetPairByName(Name);
  if LPair <> nil then
    Result := LPair.JSONValue
  else
    Result := nil;
end;

If there is any possibility that the key may not exist, it is cleaner to call GetValue() instead of Get()->JsonValue.