Thema: Delphi Json-Objekte: Merge

Einzelnen Beitrag anzeigen

Der schöne Günther

Registriert seit: 6. Mär 2013
6.108 Beiträge
 
Delphi 10 Seattle Enterprise
 
#6

AW: Json-Objekte: Merge

  Alt 11. Mai 2020, 08:41
Danke, aber ich bin jetzt noch den zusätzlichen Schritt nach der RFC gegangen sodass z.B. auch gilt:

Code:
   //   ORIGINAL       PATCH           RESULT
   //   ------------------------------------------
   //   {"a": {         {"a": {         {"a": {
   //    "b": "c",       "b": "x",       "b": "x"
   //    "d": "e"}       "d": null       }
   //   }               }               }
Sieht dann ungefähr so aus:

Delphi-Quellcode:
class function TJSONHelper.MergePatch(
  target: TJsonValue;
  const patch: TJsonValue
): TJsonValue;
var
  pair: TJsonPair;
  pairName: String;
begin
  if(patch is TJsonObject) then
    begin
      if(not (target is TJsonObject)) then
        target := TJsonObject.Create()
      else
        target := target.Clone() as TJsonValue;
      try
        Result := target.Clone() as TJsonValue;
        try
          for pair in (patch as TJsonObject) do
            begin
              pairName := pair.JsonString.Value;
              (result as TJsonObject).RemovePair(pairName).Free() ;

              if(not pair.JsonValue.Null) then
                (result as TJsonObject).AddPair(
                  pairName,
                  MergePatch(
                    (target as TJsonObject).GetValue(pair.JsonString.Value),
                    pair.JsonValue
                  )
                );
            end;
        except
          Result.Destroy(); raise;
        end;
      finally
        target.Destroy();
      end;
    end
  else
    Result := patch.Clone() as TJsonValue;
end;
  Mit Zitat antworten Zitat