最近捡起丢了10年的Delphi来玩,想试试对json的数据处理。
试了TSuperObject和TlkJSONobject,都发现拉回的数据是乱码,运行exe就报错。
测试发现获取的json源数据中间汉字的地方是乱码,导致引号不配对,引发内存错误。
后来找了文章,发现是TIdHttp在获取数据之前,要将定义的TStringStream的Encoding设置为UTF8,才可以。
贴一小段源码,看官一看就懂的:
var
b: TStringStream; //用于接收json数据的流
s1: String;
begin
b := TStringStream.Create('',65001); //65001是UTF-8
IdHTTP1.Get('http://www.weather.com.cn/data/cityinfo/101010100.html', b); //获取中国气象局公开的json数据
s1 := b.DataString;
mmoJsonContent.Text := s1; //展示原始数据
另,关于编码的定义,在System.SysUtils单元有定义:
function GetCPInfo(CodePage: Cardinal; var lpCPInfo: TCPInfo): Boolean;
begin
Result := True;
case CodePage of
// Code page identifiers understood directly by iconv_open()