Delphi XE7: How to change a JSON value using System.JSON (versus SuperObject)

試著忘記壹切 提交于 2019-12-06 11:35:26

TJSONObject does support a path evaluator similar to SuperObject. So you will not have to manually drill into the JSON value tree one object at a time (though you certainly could if you wanted to).

However, the System.JSON classes are actually NOT designed for modifying existing data (believe it or not)! They are designed for parsing data, and creating new data. All of the JSON classes that represent simple values (integers, boolean, strings) are read-only. Fortunately, the TJSONPair class allows a value to be replaced, so you will have to take advantage of that.

Try something like this:

uses
  ..., System.JSON;

var
  JsonFilename: string;
  JV: TJSONValue;
  JO: TJSONObject;
  JoX: Integer;
  JoPair: TJSONPair;
begin
  JsonFilename := ExtractFilePath(Application.ExeName) + 'product.json';

  JV := TJSONObject.ParseJSONValue(TFile.ReadAllText(JsonFilename));
  if JV = nil then raise Exception.Create('Cannot parse file: ' + JsonFilename);
  try
    JO := JV as TJSONObject;

    JoX := JO.GetValue<Integer>('AllCategories.Category[0].subCategory[0].products[0].colors.color[0].views.view[0].x');
    WriteLn('The old value of "x" is ', JoX);

    WriteLn('Changing value of "x" to "123"');
    JoPair := JO.GetValue<TJSONObject>('AllCategories.Category[0].subCategory[0].products[0].colors.color[0].views.view[0]').Get('x');
    JoPair.JsonValue.Free;
    JoPair.JsonValue := TJSONNumber.Create(123);
    WriteLn('The new value of "x" is ', JoPair.JsonValue.Value);

    SaveAsDialog.FileName := JsonFilename;
    if SaveAsDialog.Execute then TFile.WriteAllText(SaveAsDialog.FileName, JO.ToJSON);
  finally
    JV.Free;
  end;
end;

Alternatively:

uses
  ..., System.JSON;

var
  JsonFilename: string;
  JV: TJSONValue;
  JO: TJSONObject;
  JoX: TJSONPair;
begin
  JsonFilename := ExtractFilePath(Application.ExeName) + 'product.json';

  JV := TJSONObject.ParseJSONValue(TFile.ReadAllText(JsonFilename));
  if JV = nil then raise Exception.Create('Cannot parse file: ' + JsonFilename);
  try
    JO := JV as TJSONObject;

    JoX := JO.GetValue<TJSONObject>('AllCategories.Category[0].subCategory[0].products[0].colors.color[0].views.view[0]').Get('x');
    WriteLn('The old value of "x" is ', JoX.JsonValue.Value);

    WriteLn('Changing value of "x" to "123"');
    JoX.JsonValue.Free;
    JoX.JsonValue := TJSONNumber.Create(123);
    WriteLn('The new value of "x" is ', JoX.JsonValue.Value);

    SaveAsDialog.FileName := JsonFilename;
    if SaveAsDialog.Execute then TFile.WriteAllText(SaveAsDialog.FileName, JO.ToJSON);
  finally
    JV.Free;
  end;
end;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!