查找 JSONValue 的值类型(TJSONArray 或 TJSONObject)

Find Value Type of a JSONValue (TJSONArray or TJSONObject)

我想使用 Delphi XE8

中的标准库来执行此操作
if Assigned(JSONValue) then
    case JSONValue.ValueType of
      jsArray  : ProcessArrayResponse(JSONValue as TJSONArray);
      jsObject : ProcessObjectResponse(JSONValue as TJSONObject);
    end;
end;

(此示例来自 https://github.com/deltics/delphi.libs/wiki/JSON 但使用 Deltics.JSON 库)。

有人知道如何使用标准库吗?

谢谢

我进行了一些测试并发现了这种方式(似乎有效我正在测试它)

FData : TJSONArray;

...

if JSONValue is TJSONObject then
   FData := TJSONArray(JSONValue as TJSONObject)
else if JSONValue is TJSONArray then
   FData := JSONValue as TJSONArray
else if JSONValue is TJSONString then
   FData := nil;

使用is运算符来区分可能的值类型。所以,

var
  obj: TJSONObject;
  arr: TJSONArray;
....
if JSONValue is TJSONObject then
  obj := TJSONObject(JSONValue)
else if JSONValue is TJSONArray then
  arr := TJSONArray(JSONValue)
else
  // other possible types are TJSONNumber, TJSONString, TJSONTrue, TJSONFalse, TJSONNull

您可以使用 is 运算符:

if Assigned(JSONValue) then
begin
  if JSONValue is TJSONArray then
    ProcessArrayResponse(TJSONArray(JSONValue))
  else if JSONValue is TJSONObject then
    ProcessObjectResponse(TJSONObject(JSONValue));
end;

如果您想使用 case 语句,则必须创建自己的查找:

type
  JsonValueType = (jsArray, jsObject, ...);

function GetJsonValueType(JSONValue: TJSONValue): JsonValueType;
begin
  if JSONValue is TJSONArray then Exit(jsArray);
  if JSONValue is TJSONObjct then Exit(jsObject);
  ...
end;

...

if Assigned(JSONValue) then
begin
  case GetJsonValueType(JSONValue) of
    jsArray  : ProcessArrayResponse(TJSONArray(JSONValue));
    jsObject : ProcessObjectResponse(TJSONObject(JSONValue));
  end;
end;

或者:

type
  JsonValueType = (jsArray, jsObject, ...);

var
  JsonValueTypes: TDictionary<String, JsonValueType>;

...

if Assigned(JSONValue) then
begin
  case JsonValueTypes[JSONValue.ClassName] of
    jsArray  : ProcessArrayResponse(TJSONArray(JSONValue));
    jsObject : ProcessObjectResponse(TJSONObject(JSONValue));
  end;
end;

...

initialization
  JsonValueTypes := TDictionary<String, JsonValueType>.Create;
  JsonValueTypes.Add('TSONArray', jsArray);
  JsonValueTypes.Add('TSONObject', jsObject);
  ...
finalization
  JsonValueTypes.Free;