Using SuperObject in Delphi 2009. How do I deal with the situation of accessing the string value of a JSON key that might not exist?
eg with this sample code JSONgood has a key 'key2' and a value for it but JSONbad doesn't have a 'key2' and so evaluates to nil and causes an error when I try to convert it to a string. Is there a simple way to either convert the nil to a string value or detect it before I try to read it as a string and not read it?
var
ParsedJSON : ISuperObject;
s : string;
JSONgood, JSONbad: string;
begin
JSONgood, = ''
+' { '
+' "key1": "one", '
+' "key2": "not missing" '
+' } '
ParsedJSON := SOJSONgood,
s := ParsedJSON ['key2'].AsString;
showmessage(s);
JSONbad: = ''
+' { '
+' "key1": "one" '
+' } '
ParsedJSON := SOJSONbad:
s := ParsedJSON ['key2'].AsString; //key 2 does not exist so ParsedJSON ['key2'] is nil
showmeassage(s);
end;
Incidentally I did try to use X-Superobject as I understood that could deal with this but that complained that it couldn't find RegularExpressions or RTTI named in the uses clause of unit XSuperJSON, so I guess it won't work in Delphi 2009 (and I cannot afford the later Delphi versions)
edit - Adding
If Assigned(ParsedJSON ['key2']) then ...
seemed to do it but is this the proper way to do it?