delphi - 从 JSON 文件中解码 UTF-8
问题描述
我有一个带有编码 UTF-8 字符串字段的 JSON 文件,该字段表示 JPG 内容:
"ImageData": "ÿØÿà\u0000\u0010JFIF\u0000\u0001\u0002\u0000\u0000d\u0000d\u0000\u0000
我正在解析 JSON 并获取该值:
var imageString : string;
...
imageString:=jv.GetValue<string>('ImageData');
但是我在解码字节并将它们保存到文件时遇到问题
选项1。SaveBytesToFile(BytesOf(imageString),pathFile);
如您所见,标题不正确(应以 ÿØÿà 开头)
选项 2。SaveBytesToFile(TEncoding.UTF8.GetBytes(imageString),pathFile);
与选项 1 类似的问题
SaveBytesToFile 的代码:
procedure SaveBytesToFile(const Data: TBytes; const FileName: string);
var
stream: TMemoryStream;
begin
stream := TMemoryStream.Create;
try
if length(data) > 0 then
stream.WriteBuffer(data[0], length(data));
stream.SaveToFile(FileName);
finally
stream.Free;
end;
end;
我怎样才能正确解码?
解决方案
JSON 是纯文本格式,它根本没有处理二进制数据的规定。为什么图像字节没有以文本兼容格式编码,如base64、base85、base91等?否则,请改用BSON(二进制 JSON)或UBJSON(通用二进制 JSON)之类的东西,它们都支持二进制数据。
在任何情况下,BytesOf()
都会损坏字节,因为它使用用户的默认语言环境(通过TEncoding.Default
,在非 Windows 平台上是 UTF-8!),因此 ASCII 范围之外的字符会受到语言环境解释并且不会产生字节你需要。
在您的情况下,确保 JSON 库将 JSON 文件解码为 UTF-8,然后您可以简单地遍历生成的字符串(JSON 库应该为您将转义序列解析为字符)并按原样截断字符为 8 位值。根本不执行任何类型的字符集转换。例如:
var
imageString : string;
imageBytes: TBytes;
i: Integer;
...
begin
...
imageString := jv.GetValue<string>('ImageData');
SetLength(imageBytes, Length(imageString));
for i := 0 to Length(imageString)-1 do begin
imageBytes[i] := Byte(imageString[i+1]);
end;
SaveBytesToFile(imageBytes, pathFile);
...
end;
附带说明一下,您SaveBytesToFile()
可以大大简化,而不会浪费内存来复制TBytes
:
procedure SaveBytesToFile(const Data: TBytes; const FileName: string);
var
stream: TBytesStream;
begin
stream := TBytesStream.Create(Data);
try
stream.SaveToFile(FileName);
finally
stream.Free;
end;
end;
或者:
procedure SaveBytesToFile(const Data: TBytes; const FileName: string);
var
stream: TFileStream;
begin
stream := TFileStream.Create(FileName, fmCreate);
try
stream.WriteBuffer(PByte(Data)^, Length(Data));
finally
stream.Free;
end;
end;
或者:
uses
..., System.IOUtils;
procedure SaveBytesToFile(const Data: TBytes; const FileName: string);
begin
System.IOUtils.TFile.WriteAllBytes(FileName, Data);
end;
推荐阅读
- nginx - 如何使用 Nginx 删除文件扩展名后的斜杠?
- angular - MSAL.js protectedResourceMap - 需要说明将其设置为什么
- c# - 搜索多个索引并返回正确的类型
- file-upload - 如何在无头 chrome 浏览器中使用 selenium 和 autoit 进行文件上传?
- react-native - 如何在本机反应中修复“错误:未知选项--projectRoot”
- php - Youtube API V3 ETag 支持失败:内容不变但 etag 改变
- react-router - 如何访问有状态组件中的 url 参数
- html - 访问托管在服务器上的网页时出现问题
- javascript - 如何从另一个组件“隐藏/显示”“可扩展项目”组件(类星体)
- python - How to use apache airflow in a virtual environment?