Skip to content

Instantly share code, notes, and snippets.

@adilsoncarvalho
Created April 19, 2016 18:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save adilsoncarvalho/94e7d8bafe3821199993b2dda691beb3 to your computer and use it in GitHub Desktop.
Save adilsoncarvalho/94e7d8bafe3821199993b2dda691beb3 to your computer and use it in GitHub Desktop.
Parsing JSON on Delphi (the ugly way)
unit cl_ReadJSON;
interface
uses System.Json, System.SysUtils, Vcl.Dialogs, System.Classes;
procedure ReadJSON;
implementation
const StrJson =
'[{"channel":"/meta/handshake","successful":true,"version":"1.0","supportedConnectionTypes":["long-polling",'+
'"cross-origin-long-polling","callback-polling","websocket","eventsource","in-process"],"clientId":"pl4t3hchpz8t6jb0ojnzd2cccskde5r","advice":{"reconnect":"retry","interval":0,"timeout":45000}}]';
procedure ReadJSON;
var LJSONBytes: TBytes;
LJSONSObj: TJSONValue;
LJSONArray: TJSONArray;
LJSONValue, LReceive: TJSONValue;
LJPair: TJSONPair;
size: integer;
i: Integer;
ii: Integer;
Tamanho: Integer;
begin
LJSONBytes := TEncoding.ASCII.GetBytes(StrJson);
LJSONSObj := TJSONObject.ParseJSONValue(LJSONBytes, 0);
if LJSONSObj <> nil then
try
LJSONArray := LJSONSObj as TJSONArray;
Size := TJSONArray(LJSONArray).Count;
for i := 0 to Pred(Size) do
begin
ShowMessage( TJSONObject(TJSONArray(LJSONArray).Items[i]).Get('channel').JsonValue.ToString);
ShowMessage( TJSONObject(TJSONArray(LJSONArray).Items[i]).Get('successful').JsonValue.ToString);
ShowMessage( TJSONObject(TJSONArray(LJSONArray).Items[i]).Get('version').JsonValue.ToString);
ShowMessage('Conteudo do Array supportedConnectionTypes');
LJSONValue := TJSONObject(TJSONArray(LJSONArray).Items[i]).Get('supportedConnectionTypes').JsonValue;
LJPair := TJSONPair(LJSONValue);
Tamanho := TJSONArray(LJPair).Count;
//loop Leitura do array supportedConnectionTypes
for ii := 0 to Pred(Tamanho) do
begin
LReceive := TJSONArray(LJPair).Items[ii];
ShowMessage(LReceive.ToString);
end;
ShowMessage( TJSONObject(TJSONArray(LJSONArray).Items[i]).Get('clientId').JsonValue.ToString);
ShowMessage('Conteudo do Objeto advice');
LJSONValue := TJSONObject(TJSONArray(LJSONArray).Items[i]).Get('advice').JsonValue;
SHowMessage( TJSONObject(TJSONArray(LJSONValue)).Get('reconnect').JsonValue.ToString);
SHowMessage( TJSONObject(TJSONArray(LJSONValue)).Get('interval').JsonValue.ToString);
SHowMessage( TJSONObject(TJSONArray(LJSONValue)).Get('timeout').JsonValue.ToString);
end;
finally
LJSONSObj.Free;
end;
end;
end.
@sombat-buasing
Copy link

Thank you.

@adilsoncarvalho
Copy link
Author

You are welcome.

@JAVIKARU
Copy link

JAVIKARU commented May 3, 2022

Muchas gracias, funciona!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment