我通过 Synapse 以 UTF8 编码接收数据。然后它必须通过 StripNonJson 函数运行并将其“推”到 TJsonObject 类型的变量中。
function StripNonJson(s: string): string; // Убирает лишние пробелы из json-строки
var
ch: char;
inString: boolean;
begin
Result := '';
inString := false;
for ch in s do
begin
if ch = '"' then
inString := not inString;
if TCharacter.IsWhiteSpace(ch) and not inString then
continue;
Result := Result + ch;
end;
end;
function MemoryStreamToString(M: TMemoryStream): string;
begin
SetString(Result, PChar(M.Memory), M.Size div SizeOf(Char));
end;
var
json: TJSONObject;
// ...
begin
// ...
with THTTPSend.Create do
begin
try
MimeType := 'application/x-www-form-urlencoded';
Document.LoadFromStream(data);
if HTTPMethod('POST', 'http://httpbin.org/post') then
begin
WriteLn('res=' + MemoryStreamToString(Document));
json := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(StripNonJson(MemoryStreamToString(Document))), 0) as TJSONObject;
if Assigned(Json) then
begin
WriteLn('Json parsed!');
end
else
begin
WriteLn('Error parsing JSON!');
end;
end
else
begin
WriteLn('Request error: ' + IntToStr(ResultCode) + ' ' + ResultString);
end;
finally
Free;
end;
end;
end.
Kryakozyabras 出现在屏幕上,json 变量自然为空。
据我了解,您需要将 Document 从 utf8 转换为 Delphi 2010 本机 unicode,但我不知道该怎么做。
Delphi 有一个用于在编码之间转换字符串的类
TEncoding