简体   繁体   中英

JSON with SuperObject: is element an array or an object?

I get JSON from API and it have a quirk: usually it returns "tags" element as object {"x":"y"}, but if ther are no tags, it returns empty array [] instead.

I parse JSON with SuperObject, and use this code:

var
  JsonObject: ISuperObject;
  item: TSuperAvlEntry;
  temp: TStringList;
begin
{...}
      for item in JsonObject.O['tags'].AsObject do
      begin
        temp.Add(item.Name);
      end;
{...}

It works wonderfully for objects, but it crashes with Access Violation error if it's an array.

As well, if I try something like:

if JSONObject['tags'].AsArray.Length=0 then

it works fine for empty array, but crashes if it is an object.

I don't know for sure that elements may be in "tags" and thus don't know how can I use Exists() in this case.

Any ideas?

Well, looks like I found the answer myself, so I will share it.

ISuperObject has a property "DataType" which you can check, like this:

if JsonObject['tags'].DataType = stObject then
begin
  for item in JsonObject.O['tags'].AsObject do
  begin
    temp.Add(item.Name);
  end;
end;

stObject and stArray are most useful to check, but there's also: stBoolean, stDouble, stCurrency, stInt and stMethod.

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