| [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: Objectt AKey: UTF8String); procedure OnStringValue(Sender: Objectt AValue: UTF8String); procedure OnIntegerValue(Sender: Objectt AValue: Integer); procedure OnStartObject(Sender: Object procedure OnEndObject(Sender: Object property PersonName: string read FPersonName; property PersonAge: Integer read FPersonAge; end; procedure TMyJSONProcessor.OnKeyName(Sender: Objectt AKey: UTF8String); begin FCurrentKey := AKey; FInAddress := (AKey = 'address'); end; procedure TMyJSONProcessor.OnStringValue(Sender: Objectt AValue: UTF8String); begin if not FInAddress and (FCurrentKey = 'name') then FPersonName := AValue; end; procedure TMyJSONProcessor.OnIntegerValue(Sender: Objectt AValue: Integer); begin if not FInAddress and (FCurrentKey = 'age') then FPersonAge := AValue; end; procedure TMyJSONProcessor.OnStartObject(Sender: Object begin // Object started end; procedure TMyJSONProcessor.OnEndObject(Sender: Object 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: