Search code examples
jsondelphirad-studio

How to save JSONObject to JSON file in UTF‐8 encoding (RAD Studio/Delphi)?


I use RAD Studio 11. I read data from a UTF‐8‐encoded JSON file and convert them to a jsonobject. Then I make changes to this jsonobject and want to save it back to the JSON file.

However, while the data is successfully written to the file, the file is encoded with code page Windows‐1251 now. What needs to be done to retain UTF‐8 as the file encoding?

It has to be UTF‐8 because the JSON file includes Russian characters (in Windows‐1251 encoding you get ?’s).

I read from a file like this:

var inputfile:TextFile;
str:string;
// ... code omitted ... //
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;

I convert the string data to a Jsonobject like this:

LJsonObj:=TJSONObject.ParseJSONValue(str1) as TJSONobject;

I am trying to save the JsonObject like this:

var
  listStr: TStringList;
  Size: Integer;
  I: Integer;
  
  // ... code omitted ... //
  
  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;

Solution

  • No need to loop over the JSONObject. Just use:

    TFile.WriteAllBytes(Form1.filepath+'\'+form1.filename+'.json',TEncoding.UTF8.GetBytes(LJsonObj.ToJSON))