Recent

Author Topic: TJsonObject.AsJson and UTF8  (Read 2404 times)

martinrame

  • Jr. Member
  • **
  • Posts: 91
TJsonObject.AsJson and UTF8
« on: June 24, 2021, 11:51:34 pm »
Hi, I'm trying to create a simple TJsonObject with a string variable using UTF8 characters, just like this:

Code: Pascal  [Select][+][-]
  1. var
  2.   lJson: TJsonObject;
  3.   lStr: TStringList;
  4. begin
  5.   lJson := TJsonObject.Create;
  6.   lJson.Add('value', 'Valoración');
  7.   lStr := TStringList.Create;
  8.   lStr.Text := lJson.AsJson;
  9.   lStr.SaveToFile('/tmp/salida.json');
  10.   lStr.Free;
  11.   lJson.Free;
  12. end;

The resulting file "salida.json" contanis this:

Code: Pascal  [Select][+][-]
  1. { "value": "Valoración" }

As you can see the output does not respect the UTF8 value.

I'm using Lazarus 1.9.0 and FPC 3.1.1.

ASerge

  • Hero Member
  • *****
  • Posts: 1851
Re: TJsonObject.AsJson and UTF8
« Reply #1 on: June 25, 2021, 08:47:21 pm »
As you can see the output does not respect the UTF8 value.
Workaround (Lazarus 2.0.12, FPC 3.2.0):
Code: Pascal  [Select][+][-]
  1. {$MODE OBJFPC}
  2. {$LONGSTRINGS ON}
  3.  
  4. uses Classes, fpjson;
  5.  
  6. var
  7.   LJson: TJsonObject;
  8.   LStr: TStringList;
  9.   S: string;
  10. begin
  11.   LJson := TJsonObject.Create;
  12.   try
  13.      S := 'Valoración';
  14.      LJson.Add('value', S);
  15.      LStr := TStringList.Create;
  16.      try
  17.         LStr.Text := LJson.AsJson;
  18.         LStr.SaveToFile('./tmp/salida.json');
  19.      finally
  20.        LStr.Free;
  21.      end;
  22.   finally
  23.     LJson.Free;
  24.   end;
  25. end.

martinrame

  • Jr. Member
  • **
  • Posts: 91
Re: TJsonObject.AsJson and UTF8
« Reply #2 on: June 25, 2021, 08:50:38 pm »
Did you just replace the hardcoded 'Valoración' inside the json.add by a string variable?.

ASerge

  • Hero Member
  • *****
  • Posts: 1851
Re: TJsonObject.AsJson and UTF8
« Reply #3 on: June 25, 2021, 09:02:51 pm »
Did you just replace the hardcoded 'Valoración' inside the json.add by a string variable?.
Yes. But this work.

martinrame

  • Jr. Member
  • **
  • Posts: 91
Re: TJsonObject.AsJson and UTF8
« Reply #4 on: June 25, 2021, 09:08:19 pm »
Thanks, I'll try that.

 

TinyPortal © 2005-2018