Membaca data json dengan delphi 7

Berikut kode untuk membaca data json dengan delphi 7.

uses
 IdHTTP, IdException, IdStack, uLkJSON;

procedure TForm1.Button1Click(Sender: TObject);
var
 sJSON: String;
 js, Items, Item: TlkJSONBase;
 I, J: Integer;
 IdHTTP: TIdHTTP;
 resp: TMemoryStream;
begin
 IdHTTP := TIdHTTP.Create(Self);
 resp := TMemoryStream.Create;
 try
 try
 IdHTTP.Get('http://localhost/experiments/json/index.txt', resp);
 resp.Position := 0;
 memo1.Lines.LoadFromStream(resp);

SetLength(sJSON, resp.Size);
 resp.Position := 0;
 resp.Write(sJSON[1], Length(sJSON));

js := TlkJSON.ParseText(sJSON);
 for I := 0 to Pred(js.Count) do
 begin
 Items := js.Child[I].Field['items'];
 for J := 0 to Pred(Items.Count) do begin
 Item := Items.Child[J];
 Memo2.Lines.Add(VarToStr(Item.Field['region_id'].Value));
 Memo2.Lines.Add(VarToStr(Item.Field['average_cover'].Value));
 Memo2.Lines.Add(VarToStr(Item.Field['average_growth'].Value));
 end;
 end;

except
 // this exception class covers the HTTP protocol errors; you may read the
 // response code using ErrorCode property of the exception object, or the
 // same you can read from the ResponseCode property of the TIdHTTP object
 on E: EIdHTTPProtocolException do
 ShowMessage('Indy raised a protocol error!' + sLineBreak +
 'HTTP status code: ' + IntToStr(E.ReplyErrorCode) + sLineBreak +
 'Error message' + E.Message);
 // this exception class covers the cases when the server side closes the
 // connection with a client in a "peaceful" way
 on E: EIdConnClosedGracefully do
 ShowMessage('Indy reports, that connection was closed gracefully!');
 // this exception class covers all the low level socket exceptions
 on E: EIdSocketError do
 ShowMessage('Indy raised a socket error!' + sLineBreak +
 'Error code: ' + IntToStr(E.LastError) + sLineBreak +
 'Error message' + E.Message);
 // this exception class covers all exceptions thrown by Indy library
 on E: EIdException do
 ShowMessage('Indy raised an exception!' + sLineBreak +
 'Exception class: ' + E.ClassName + sLineBreak +
 'Error message: ' + E.Message);
 // this exception class is a base Delphi exception class and covers here
 // all exceptions different from those listed above
 on E: Exception do
 ShowMessage('A non-Indy related exception has been raised!');
 end;
 finally
 IdHTTP.Free;
 resp.Free;
 end;
end;


Untuk membaca json, kode diatas menggunakan library tambahan yaitu lkjson.  Wassalam.

2 thoughts on “Membaca data json dengan delphi 7

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s