如何以UTF8编码将JSONObject保存到json文件Rad Studio/Delphi

APT*_*MKA 1 delphi json pascal rad-studio

我使用 Rad studio 11。我从 json 文件(文件是 UTF8 编码)读取信息并转换为 jsonobject。然后我对此 jsonobject 进行更改并希望保存到 json 文件。信息已成功写入文件,但文件具有 Windows-1251 编码。需要做什么才能使文件编码为UTF8?它需要我,因为 json 文件包含俄语符号(在 Windows-1251 编码中它看起来像“?”)。

我从这样的文件中读取:

var inputfile:TextFile;
str:string;
...
if OpenDialog1.Execute then  begin
  AssignFile(inputfile, OpenDialog1.FileName);
  reset(inputfile);

  while not Eof(inputfile) do
  begin
    ReadLn(inputfile, str);
    str1 := str1+UTF8ToANSI(str);
  end;

  closefile(inputfile);
end;
Run Code Online (Sandbox Code Playgroud)

我像这样转换为 Jsonobject:

LJsonObj:=TJSONObject.ParseJSONValue(str1) as TJSONobject;
Run Code Online (Sandbox Code Playgroud)

尝试像这样保存 JsonObject:

var   
  listStr: TStringList;
  Size: Integer;
  I: Integer;
  
...
  
  Size := Form3.LJsonObj.Count;
  liststr := TStringList.Create;

  try
    listStr.Add('{');

    if Size > 0 then
      listStr.Add(LJsonObj.Get(0).ToString);
   
    showmessage(LJsonObj.Get(0).ToString);

    for I := 1 to Size - 1 do
    begin
      listStr.Add(',');
      listStr.Add(ANSITOUTF8(LJsonObj.Get(I).ToString));
    end;

    listStr.Add('}');
    // Form1.filepath-is path of file,form1.filename-name of file without file extension 
    listStr.SaveToFile(Form1.filepath+'\'+form1.filename+'.json');
  finally
    listStr.Free;
  end;
Run Code Online (Sandbox Code Playgroud)

Rem*_*eau 7

为什么要使用旧式 Pascal 文件 I/O 来读取文件?为什么要在 UTF-8 和ANSI之间转换?您正在使用 Delphi 的 Unicode 版本,您根本不应该处理 ANSI。

任何状况之下:

  • 读取文件时,请考虑使用TStringList.LoadFromFile()orTFile.ReadAllText()代替。两者都允许您指定 UTF-8 作为源编码。

  • 写入文件时,请考虑使用TStringList.SaveToFile()orTFile.WriteAllText()代替。两者都允许您指定 UTF-8 作为目标编码。

例如:

var
  inputfile: TStringList;
  str1: string;
  ...
begin
  ...
  inputfile := TStringList.Create;
  try
    inputfile.LoadFromFile(OpenDialog1.FileName, TEncoding.UTF8);
    str1 := inputfile.Text;
  finally
    inputfile.Free;
  end;
  ...
end;

...

var   
  listStr: TStringList;
  ...
begin
  ...
  listStr.SaveToFile(Form1.filepath + '\' + form1.filename + '.json', TEncoding.UTF8);
  ...
end;
Run Code Online (Sandbox Code Playgroud)
var
  str1: string;
  ...
begin
  ...
  str1 := TFile.ReadAllText(OpenDialog1.FileName, TEncoding.UTF8);
  ...
end;

...

var
  listStr: TStringList;
  ...
begin
  ...
  TFile.WriteAllText(listStr.Text, TEncoding.UTF8);
  ...
end;
Run Code Online (Sandbox Code Playgroud)

请注意,您实际上并不需要使用 aTStringList来手动构建 JSON 语法。 TJSONObjectToString()ToJSON()方法可以为您处理这个问题。但是,如果您确实想手动构建自己的 JSON 语法,请考虑使用TJSONObjectBuilderorTJsonTextWriter来代替。