I'm using Delphi XE3. I have a JSON stream where an object can be null. That is, I can receive:
"user":null
or
"user":{"userName":"Pep","email":"[email protected]"}
I want to discriminate both cases, and I tried with this code:
var
jUserObject: TJSONObject;
jUserObject := TJSONObject(Get('user').JsonValue);
if (jUserObject.Null)
then begin
FUser := nil;
end else begin
FUser := TUser.Create;
with FUser, jUserObject do begin
FEmail := TJSONString(Get('email').JsonValue).Value;
FUserName := TJSONString(Get('userName').JsonValue).Value;
end;
end;
If I put a breakpoint right in line if (jUserObject.Null) then begin and I mouse over jUserObject.Null it says jUserObject.Null = True if "user":null and it says jUserObject.Null = False if "user":{"userName":"Pep","email":"[email protected]"}
However, if I step into that line with the debugger, jUserObject.Null calls the following XE3 library code:
function TJSONAncestor.IsNull: Boolean;
begin
Result := False;
end;
So I always get a False for my if sentence, even if "user":null.
I suppose I always have the workaround of catching the exception that is raised when "user":null and Get('email').JsonValue is executed in order to discriminate if the value is null or not, but that does not seem so elegant.
How is one supposed to detect if an JSON object has a null value in the JSON stream?