简体   繁体   中英

How to deal with missing JSON key when using SuperObject to get key values?

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?

Here is a solution I came up with.

It works a bit like the MySQL function IFNULL(Value, DefaultValueIfNull) and will return either the string value associated with the key passed or, of the key doesn't exist, it returns the substitute text passed into the function

function MissingKeySafeStr(theobject: ISuperObject; key: string; SubstituteText: string) : string;
   begin
   if theobject[key] = nil then
     Result :=  SubstituteText
   else
     Result :=  theobject[key].AsString
   end;

usage

procedure TForm1.Button1Click(Sender: TObject);
var 
   s : string;
   obj : ISuperObject;
begin
 s := '{"name":"jim"}';
 obj := SO(s);
 ShowMessage(MissingKeySafeStr(obj,'age', 'age key missing'));  //displays ''age key missing'
 ShowMessage(MissingKeySafeStr(obj,'name, 'name key missing'));  //displays 'jim'

end;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM