| [Previous][Up] |
TJSONEventReader provides event-based JSON parsing similar to SAX parsing for XML. As the parser encounters different JSON elements, it fires corresponding events that you can handle to process the data.
This approach is memory-efficient for large JSON documents since it doesn't load the entire structure into memory. You only need to handle the events for the data you're interested in processing.
Basic usage involves:
Here's a complete example that parses JSON and extracts specific values:
program JSONEventReaderDemo; {$mode objfpc}{$H+} uses Classes, SysUtils, jsonreader; type TMyJSONProcessor = class private FPersonName: string; FPersonAge: Integer; FInAddress: Boolean; FCurrentKey: string; public procedure OnKeyName(Sender: TObject; const AKey: UTF8String); procedure OnStringValue(Sender: TObject; const AValue: UTF8String); procedure OnIntegerValue(Sender: TObject; const AValue: Integer); procedure OnStartObject(Sender: TObject); procedure OnEndObject(Sender: TObject); property PersonName: string read FPersonName; property PersonAge: Integer read FPersonAge; end; procedure TMyJSONProcessor.OnKeyName(Sender: TObject; const AKey: UTF8String); begin FCurrentKey := AKey; FInAddress := (AKey = 'address'); end; procedure TMyJSONProcessor.OnStringValue(Sender: TObject; const AValue: UTF8String); begin if not FInAddress and (FCurrentKey = 'name') then FPersonName := AValue; end; procedure TMyJSONProcessor.OnIntegerValue(Sender: TObject; const AValue: Integer); begin if not FInAddress and (FCurrentKey = 'age') then FPersonAge := AValue; end; procedure TMyJSONProcessor.OnStartObject(Sender: TObject); begin // Object started end; procedure TMyJSONProcessor.OnEndObject(Sender: TObject); begin FInAddress := False; end; var Reader: TJSONEventReader; Processor: TMyJSONProcessor; JSONData: string; begin JSONData := '{"name": "Alice Smith", "age": 28, "address": {"street": "123 Oak St", "city": "Springfield"}}'; Processor := TMyJSONProcessor.Create; Reader := TJSONEventReader.Create(JSONData, []); try // Assign event handlers Reader.OnKeyName := @Processor.OnKeyName; Reader.OnStringValue := @Processor.OnStringValue; Reader.OnIntegerValue := @Processor.OnIntegerValue; Reader.OnStartObject := @Processor.OnStartObject; Reader.OnEndObject := @Processor.OnEndObject; // Parse the JSON Reader.Execute; // Display results Writeln('Person Name: ', Processor.PersonName); Writeln('Person Age: ', Processor.PersonAge); finally Reader.Free; Processor.Free; end; end.
The event-based approach is ideal when you need to: