首页 > 解决方案 > 从 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);

如您所见,标题不正确(应以 ÿØÿà 开头)

选项1

选项 2。SaveBytesToFile(TEncoding.UTF8.GetBytes(imageString),pathFile);

与选项 1 类似的问题

选项2

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;

我怎样才能正确解码?

标签: delphifiremonkey

解决方案


JSON 是纯文本格式,它根本没有处理二进制数据的规定。为什么图像字节没有以文本兼容格式编码,如base64base85base91等?否则,请改用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;

推荐阅读