-
Notifications
You must be signed in to change notification settings - Fork 14
/
JSONDoc.pas
executable file
·127 lines (107 loc) · 2.62 KB
/
JSONDoc.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
unit JSONDoc;
// ***********************************************************************
//
// JSON Document Component
//
//
// July 2010 - version 1.0
// February 2016 - version 1.1
//
// ***********************************************************************
interface
uses
System.Classes, System.JSON;
type
TJSONDocument = class(TComponent)
private
FRootValue: TJSONValue;
FJsonText: string;
FOnChange: TNotifyEvent;
procedure SetJsonText(const Value: string);
protected
procedure FreeRootValue;
procedure DoOnChange; virtual;
procedure ProcessJsonText;
public
class function StripNonJson(s: string): string; inline;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function IsActive: boolean;
function EstimatedByteSize: integer;
property RootValue: TJSONValue read FRootValue;
published
property JsonText: string read FJsonText write SetJsonText;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
implementation
uses
System.SysUtils, System.Character;
{ TJSONDocument }
constructor TJSONDocument.Create(AOwner: TComponent);
begin
inherited;
FRootValue := nil;
FJsonText := '';
end;
destructor TJSONDocument.Destroy;
begin
FreeRootValue;
inherited;
end;
procedure TJSONDocument.FreeRootValue;
begin
if Assigned(FRootValue) then
FreeAndNil(FRootValue);
end;
procedure TJSONDocument.DoOnChange;
begin
if Assigned(FOnChange) then
FOnChange(self);
end;
function TJSONDocument.EstimatedByteSize: integer;
begin
if IsActive then
Result := FRootValue.EstimatedByteSize
else
Result := 0;
end;
function TJSONDocument.IsActive: boolean;
begin
Result := RootValue <> nil;
end;
procedure TJSONDocument.SetJsonText(const Value: string);
begin
if FJsonText <> Value then
begin
FreeRootValue;
FJsonText := Value;
if FJsonText <> '' then
ProcessJsonText;
if not IsActive then
FJsonText := '';
end;
end;
procedure TJSONDocument.ProcessJsonText;
var s: string;
begin
FreeRootValue;
s := StripNonJson(JsonText);
FRootValue := TJSONObject.ParseJSONValue(BytesOf(s),0);
DoOnChange;
end;
class function TJSONDocument.StripNonJson(s: string): string;
var ch: char; inString: boolean;
begin
Result := '';
inString := false;
for ch in s do
begin
if ch = '"' then
inString := not inString;
if ch.IsWhiteSpace and not inString then
continue;
Result := Result + ch;
end;
end;
end.