Search code examples
arraysjsondelphiobjectdelphi-xe8

Find Value Type of a JSONValue (TJSONArray or TJSONObject)


I would like to do this with the standard Library in Delphi XE8

if Assigned(JSONValue) then
    case JSONValue.ValueType of
      jsArray  : ProcessArrayResponse(JSONValue as TJSONArray);
      jsObject : ProcessObjectResponse(JSONValue as TJSONObject);
    end;
end;

(this sample come from https://github.com/deltics/delphi.libs/wiki/JSON but using Deltics.JSON library).

Does Anyone know how to do it with standard library ?

thank you


Solution

  • You could use the is operator:

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

    If you want to use a case statement then you will have to create your own lookup:

    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;
    

    Or:

    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;