thomaserlang / delphi-json

JSON parser for Delphi.
83 stars 32 forks source link

Handling null value #16

Closed cdsaenz closed 5 years ago

cdsaenz commented 5 years ago

I have this response from a REST API:

{
   "status": true,
   "result": "OK",
   "json" :  {
          "last_name": "Wilson" 
        }
}

That sometimes brings an empty "json" element.. as null:

{
   "status": true,
   "result": "ERROR",
   "json" : null
}

And the code that I use is something like this. Works perfect in the first case, but fails when "json" has a null value.. How can I trap that error? I tried Assigned, nil, VarIsNull, etc but always get a violation.

Must be something simple but escapes me - Thanks for your help and this great utility.

JResp             := TdJSON.Parse(Content);
JResult           := JResp['result'].AsString;

if ( JResp['json'] <> nil ) then begin
      UserLast := JResp['json']['last_name'].AsString;
end;
cdsaenz commented 5 years ago

After investigating.. I think this code will do?

if ( Assigned(JResp['json'].Items) ) then begin

thomaserlang commented 5 years ago

You can do:

if (JResp['json'].Value <> null) then

Since the values are stored as variants.

thomaserlang commented 5 years ago

Just added IsNull.

if (not JResp['json'].IsNull) then
cdsaenz commented 5 years ago

Thanks! works perfect! This unit is a real timesaver.