I use Rad studio 11. I read information from json file (file is UTF8 encoded) and convert to jsonobject. Then I make changes to this jsonobject and want to save to json file. The information is successfully written to the file, but the file has the Windows-1251 encoding. What needs to be done to make the file encoding UTF8? It's need me because json file include russian symbols (in Windows-1251 encoding it's looking like '?').
I read from a file like this:
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;
I convert to Jsonobject like this:
LJsonObj:=TJSONObject.ParseJSONValue(str1) as TJSONobject;
Trying to save JsonObject like this:
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;
CodePudding user response:
Why are you reading the file using old-style Pascal file I/O? And why are you converting between UTF-8 and ANSI? You are using a Unicode version of Delphi, you should not be dealing with ANSI at all.
In any case:
When reading the file, consider using
TStringList.LoadFromFile()orTFile.ReadAllText()instead. Both allow you to specify UTF-8 as the source encoding.When writing the file, consider using
TStringList.SaveToFile()orTFile.WriteAllText()instead. Both allow you to specify UTF-8 as the target encoding.
For example:
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;
var
str1: string;
...
begin
...
str1 := TFile.ReadAllText(OpenDialog1.FileName, TEncoding.UTF8);
...
end;
...
var
listStr: TStringList;
...
begin
...
TFile.WriteAllText(listStr.Text, TEncoding.UTF8);
...
end;
Note that you don't really need to use a TStringList to build up JSON syntax manually. TJSONObject has ToString() and ToJSON() methods to handle that for you. But, if you really want to build up your own JSON syntax manually, consider using TJSONObjectBuilder or TJsonTextWriter for that purpose instead.
CodePudding user response:
No need to loop over the JSONObject. Just use:
TFile.WriteAllBytes(Form1.filepath '\' form1.filename '.json',TEncoding.UTF8.GetBytes(LJsonObj.ToJSON))
