如何为现有的.json文件添加一个对象和一对?

时间:2016-10-09 22:20:22

标签: json delphi

我有一个代码可以更改现有JSON文件中已确定对的值,并且运行正常。现在我需要在这个文件中添加一个对象和一对,使用相同的代码。那怎么办?

谢谢。

uses
 System.Json, ShFolder, System.IOUtils;

...

function GetSpecialFolderPath(folder : integer) : string;
 const
   SHGFP_TYPE_CURRENT = 0;
 var
   path: array [0..MAX_PATH] of char;
 begin
   if SUCCEEDED(SHGetFolderPath(0,folder,0,SHGFP_TYPE_CURRENT,@path[0])) then
     Result := path
   else
     Result := '';
 end;

procedure ChangeChromeSetting(const ATarget, Avalue: string);
var
  specialfolder: integer;
  caminhochrome: String;
  JSONObj, Obj: TJSONObject;
  JSONPair: TJSONPair;
  OldValue: string;
begin
  specialFolder := CSIDL_LOCAL_APPDATA;
  caminhochrome := GetSpecialFolderPath(specialFolder);
  caminhochrome := caminhochrome + '\Google\Chrome\User Data\Local State';

 if fileexists(caminhochrome) then
  begin
    Obj := TJSONObject.Create;
    JSONObj := TJSONObject.ParseJSONValue(TFile.ReadAllText(caminhochrome)) as TJSONObject;
    if not Assigned(JSONObj) then raise Exception.Create('Cannot read file: ' + caminhochrome);
    try
      OldValue := JSONObj.GetValue<string>(ATarget);
      if not SameText(OldValue, Avalue) then
      begin
        JSONPair := JSONObj.Get(ATarget);
        JSONPair.JsonValue.Free;
        JSONPair.JsonValue := TJSONString.Create(Avalue);
        ///////////////////////////////////////////////////
        Obj.AddPair('enabled', TJSONBool.Create(false)); // Trying add pair
        JSONObj.AddPair('hardware_acceleration_mode', Obj);  // Trying add object
        //////////////////////////////////////////////////
        TFile.WriteAllText(caminhochrome, JSONObj.ToJSON); // Don't add object and pair
      end;
    finally
      JSONObj.Free;
    end;
  end;
end;


procedure TForm1.Button1Click(Sender: TObject);
begin
  ChangeChromeSetting('hardware_acceleration_mode_previous', 'false');
end;

这是我正在等待的结果

"hardware_acceleration_mode":{"enabled":false}

1 个答案:

答案 0 :(得分:0)

您的代码有点令人困惑,因为您将一些名称作为参数传递,但随后在函数内部硬编码。抽象功能是一种很好的做法,但在您抽象之前,您确实需要确保代码正常工作。我将展示不试图抽象的代码。一旦你满意,它就会按照你的需要行事,然后随意抽象出来。

此代码执行我认为您的意图:

var
  root: TJSONObject;
  value: TJSONObject;
  prev: string;
begin
  root := TJSONObject.ParseJSONValue(TFile.ReadAllText(FileName)) as TJSONObject;
  try
    prev := root.GetValue<string>('hardware_acceleration_mode_previous');
    if not SameText(prev, 'false') then
    begin
      // remove existing value, if it exists
      root.RemovePair('hardware_acceleration_mode').Free;

      // create a new object, and initialise it
      value := TJSONObject.Create;
      value.AddPair('enabled', 'false');

      // add the object at the root level
      root.AddPair('hardware_acceleration_mode', value);

      // save to file
      TFile.WriteAllText(FileName, root.ToJSON);
    end;
  finally
    root.Free;
  end;
end;

请注意,我确保没有内存泄漏。我使用了RemovePair来确保如果存在名为hardware_acceleration_mode的现有值,则首先将其删除。