Накидал вам функцию (проверил - работает):
unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
System.JSON,
System.NetEncoding,
System.IOUtils;
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function ExtractPDFContentBase64(const AJSONString : String; out AFileName : String) : boolean;
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
function TForm1.ExtractPDFContentBase64(const AJSONString : String; out AFileName : String) : boolean;
Var AJSONObject, AJSONObjectBody, AJSONObjectNextStep : TJSONObject;
ACode : Integer;
AStreamSource, AStreamDest : TMemoryStream;
ADecodeByteCount : Integer;
ABase64 : String;
begin
// Выставляем результат функции в False
Result:=False;
// Парсим JSON строку в JSON объект
AJSONObject:=TJSONObject(TJSONObject.ParseJSONValue(AJSONString));
if Not Assigned(AJSONObject) then
exit;
// Проверям поле code на предмет содержания http code 200 (это я домыслил, можно удалить)
if Not AJSONObject.TryGetValue('code', ACode) then
exit;
if ACode <> 200 then
exit;
// Извлекаем body
if Not AJSONObject.TryGetValue('body', AJSONObjectBody) then
exit;
if Not Assigned(AJSONObjectBody) then
exit;
// Из body извлекаем instanceId - будем использовать как имя файла
if Not AJSONObjectBody.TryGetValue('instanceId', AFileName) then
exit;
// Склеиваем полное имя файла
// AFileName:=TPath.Combine(TPath.GetSharedDownloadsPath, AFileName + '.pdf');
AFileName:=TPath.Combine(TPath.GetSharedDownloadsPath, AFileName + '.jpeg'); // Я тестил на картинке
// Извлекаем nextStep
if Not AJSONObjectBody.TryGetValue('nextStep', AJSONObjectNextStep) then
exit;
if Not Assigned(AJSONObjectNextStep) then
exit;
// Содаем поток-источник и помещаем в него base64
AStreamSource:=TMemoryStream.Create;
if Not AJSONObjectNextStep.TryGetValue('pdf', ABase64) then
exit;
AStreamSource.WriteBuffer(Pointer(ABase64)^, Length(ABase64) * 2); // Длину строки умножаем на 2, так как строка юникод
AStreamSource.Position:=0;
// Создаем поток-назначение
AStreamDest:=TMemoryStream.Create;
// Декодируем base64 из текста в потоке AStreamSource в бинарные данные в поток AStreamDest
ADecodeByteCount:=TNetEncoding.Base64.Decode(AStreamSource, AStreamDest);
// Проверяем сколько байт было декодировано
if (ADecodeByteCount > 0) then
begin
AStreamDest.Position:=0;
try
// Сохраняем поток с бинарными данными в файл с ранее собранным именем
AStreamDest.SaveToFile(AFileName);
except
exit;
end;
end;
// Выставляем результат функции в True
Result:=True;
end;
procedure TForm1.FormCreate(Sender: TObject);
Var AJSONString : String;
AFileName : String;
begin
AJSONString:=TFile.ReadAllText('d:\JSON_example.txt');
if ExtractPDFContentBase64(AJSONString, AFileName) then
begin
// Что то делаем с PDF файлом AFileName
end;
end;
end.