Sign in Join
Wiki copytemporary

fcl-json/pl: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: fcl-json/pl

OldNewLine
1+# Informacje
2+
3+fcl-json jest implementacją [[JSON]].
4+
5+Zawiera moduły takie jak:
6+
7+- fpjson: moduł podstawowy, który implementuje TJsonData i jego klasy potomne, np. TJsonObject
8+- jsonParser: implementuje parser TJsonParser, użyty w przykładzie z JsonViewer poniżej
9+- jsonConf: implementuje TJsonConfig, który jest przydatny do odczytu/zapisu danych aplikacji z/do plików
10+- jsonScanner: leksykalny analizator źródła JSON
11+
12+> **Note:** W fpjson dostęp np. do `SomeJSONObject.Integers['price']` może wywołać zdarzenie SIGSEGV/Access Violation (naruszenie dostępu), jeśli ta zmienna Integers nie istnieje. Jest to pozornie celowe, patrz [[http://bugs.freepascal.org/view.php?id=22273]]. Będziesz musiał użyć metody Find (dostępnej od wersji FPC 2.6.2), aby najpierw sprawdzić, czy element ('price' w tym przykładzie) istnieje.
13+
14+# Przesyłanie strumieniowe
15+
16+fcl-json zawiera moduł "fpjsonrtti", który służy do ładowania obiektów (instancji TObject) z formatu JSON lub do zapisywania ich w formacie JSON.
17+
18+Zobacz [[Streaming JSON]] na krótkim przykładzie.
19+
20+# Przykłady
21+
22+## Pierwsze kroki
23+
24+``` pascal
25+
26+uses
27+ fpjson, jsonparser;
28+
29+procedure JSONTest;
30+var
31+ jData : TJSONData;
32+ jObject : TJSONObject;
33+ jArray : TJSONArray;
34+ s : String;
35+begin
36+
37+ // jest to tylko minimalna próbka tego, co można zrobić z tym interfejsem API
38+
39+ // utwórz z ciągu string
40+ jData := GetJSON('{"Fld1" : "Hello", "Fld2" : 42, "Colors" : ["Red", "Green", "Blue"]}');
41+
42+ // wyjście jako płaski ciąg string
43+ s := jData.AsJSON;
44+
45+ // wyjście jest ładnie sformatowanym JSON
46+ s := jData.FormatJSON;
47+
48+ // rzutowanie jako TJSONObject, aby ułatwić dostęp
49+ jObject := TJSONObject(jData);
50+
51+ // pobierz wartość Fld1
52+ s := jObject.Get('Fld1');
53+
54+ // zmień wartość Fld2
55+ jObject.Integers['Fld2'] := 123;
56+
57+ // pobierz drugi kolor
58+ s := jData.FindPath('Colors[1]').AsString;
59+
60+ // dodaj nowy element
61+ jObject.Add('Happy', True);
62+
63+ // dodaj nową pod-tablicę
64+ jArray := TJSONArray.Create;
65+ jArray.Add('North');
66+ jArray.Add('South');
67+ jArray.Add('East');
68+ jArray.Add('West');
69+ jObject.Add('Directions', jArray);
70+
71+end;
72+```
73+
74+## Przenoszenie elementów
75+
76+``` pascal
77+uses
78+ Classes, TypInfo, fpjson, jsonparser;
79+
80+procedure JSONItems(Info: TStrings);
81+var
82+ jData : TJSONData;
83+ jItem : TJSONData;
84+ i, j: Integer;
85+ object_name, field_name, field_value, object_type, object_items: String;
86+begin
87+ jData := GetJSON('{"A":{"field1":0, "field2": false},"B":{"field1":0, "field2": false}}');
88+
89+ for i := 0 to jData.Count - 1 do
90+ begin
91+ jItem := jData.Items[i];
92+
93+ object_type := GetEnumName(TypeInfo(TJSONtype), Ord(jItem.JSONType));
94+ object_name := TJSONObject(jData).Names[i];
95+ WriteStr(object_items, jItem.Count);
96+
97+ Info.Append('object type: ' + object_type + '|object name: ' + object_name + '|number of fields: ' + object_items);
98+
99+ for j := 0 to jItem.Count - 1 do
100+ begin
101+ field_name := TJSONObject(jItem).Names[j];
102+ field_value := jItem.FindPath(TJSONObject(jItem).Names[j]).AsString;
103+
104+ Info.Append(field_name + '|' + field_value);
105+ end;
106+ end;
107+
108+ jData.Free;
109+end;
110+```
111+
112+## Zapisz/wczytaj pozycję/rozmiar okna dialogowego
113+
114+``` pascal
115+uses
116+ jsonConf;
117+
118+procedure TfmMain.SaveOptionsPos;
119+var
120+ c: TJSONConfig;
121+begin
122+ c:= TJSONConfig.Create(Nil);
123+ try
124+ c.Filename:= 'form.cfg';
125+ c.SetValue('/dialog/max', WindowState=wsMaximized);
126+ if WindowState<>wsMaximized then
127+ begin
128+ c.SetValue('/dialog/posx', Left);
129+ c.SetValue('/dialog/posy', Top);
130+ c.SetValue('/dialog/sizex', Width);
131+ c.SetValue('/dialog/sizey', Height);
132+ end;
133+ finally
134+ c.Free;
135+ end;
136+end;
137+
138+procedure TfmMain.LoadOptionsPos;
139+var
140+ nLeft, nTop, nW, nH: Integer;
141+ c: TJSONConfig;
142+begin
143+ c:= TJSONConfig.Create(Nil);
144+ try
145+ c.Filename:= 'form.cfg';
146+
147+ nLeft:= c.GetValue('/dialog/posx', Left);
148+ nTop:= c.GetValue('/dialog/posy', Top);
149+ nW:= c.GetValue('/dialog/sizex', Width);
150+ nH:= c.GetValue('/dialog/sizey', Height);
151+ SetBounds(nLeft, nTop, nW, nH);
152+
153+ if c.GetValue('/dialog/max', false) then
154+ WindowState:= wsMaximized;
155+ finally
156+ c.Free;
157+ end;
158+end;
159+```
160+
161+W pliku form.cf zapisze się struktura JSON podobna do tej: { "dialog" : { "max" : false, "posx" : 141, "posy" : 247, "sizex" : 320, "sizey" : 240 } }
162+
163+## Zapisz/wczytaj TStringList
164+
165+``` pascal
166+//Przykład ścieżki: '/list_find'
167+
168+procedure SLoadStringsFromFile(cfg: TJsonConfig; const path: String; List: TStrings);
169+var
170+ i: Integer;
171+ s: UnicodeString;
172+begin
173+ List.Clear;
174+ for i:= 0 to OptMaxHistoryItems-1 do
175+ begin
176+ s:= cfg.GetValue(path+'/'+inttostr(i), '');
177+ if s='' then
178+ Break;
179+ List.Add(Utf8Encode(s));
180+ end;
181+end;
182+
183+procedure SSaveStringsToFile(cfg: TJsonConfig; const path: String; List: TStrings);
184+var
185+ i: Integer;
186+ s: String;
187+begin
188+ for i:= 0 to OptMaxHistoryItems-1 do
189+ begin
190+ if i<List.Count then
191+ s:= List[i]
192+ else
193+ s:= '';
194+ cfg.SetDeleteValue(path+'/'+inttostr(i), Utf8Decode(s), '');
195+ end;
196+end;
197+```
198+
199+## Przykład z JsonViewer
200+
201+Przykład użycia można znaleźć w narzędziu Lazarus jsonviewer (znajdującym się w lazarus/tools/jsonviewer). W szczególności, ta część narzędzia pokazuje, jak używać json:
202+
203+``` pascal
204+procedure TMainForm.OpenFile(Const AFileName : String);
205+var
206+ S : TFileStream;
207+ P : TJSONParser;
208+ D : TJSONData;
209+begin
210+ S:=TFileStream.Create(AFileName,fmOpenRead);
211+ try
212+ P:=TJSONParser.Create(S);
213+ try
214+ P.Strict:=FStrict;
215+ D:=P.Parse;
216+ finally
217+ P.Free;
218+ end;
219+ finally
220+ S.Free;
221+ end;
222+ FFileName:=AFileName;
223+ SetCaption;
224+ FreeAndNil(FRoot);
225+ FRoot:=D;
226+ ShowJSONDocument;
227+end;
228+
229+procedure TMainForm.ShowJSONDocument;
230+begin
231+ with TVJSON.Items do
232+ begin
233+ BeginUpdate;
234+ try
235+ TVJSON.Items.Clear;
236+ SHowJSONData(Nil,FRoot);
237+ with TVJSON do
238+ if (Items.Count>0) and Assigned(Items[0]) then
239+ begin
240+ Items[0].Expand(False);
241+ Selected:=Items[0];
242+ end;
243+ finally
244+ EndUpdate;
245+ end;
246+ end;
247+end;
248+
249+procedure TMainForm.ShowJSONData(AParent : TTreeNode; Data : TJSONData);
250+var
251+ N,N2 : TTreeNode;
252+ I : Integer;
253+ D : TJSONData;
254+ C : String;
255+ S : TStringList;
256+begin
257+ N:=Nil;
258+ if Assigned(Data) then
259+ begin
260+ case Data.JSONType of
261+ jtArray,
262+ jtObject:
263+ begin
264+ if (Data.JSONType=jtArray) then
265+ C:=SArray
266+ else
267+ C:=SObject;
268+ N:=TVJSON.Items.AddChild(AParent,Format(C,[Data.Count]));
269+ S:=TstringList.Create;
270+ try
271+ for I:=0 to Data.Count-1 do
272+ if Data.JSONtype=jtArray then
273+ S.AddObject(IntToStr(I),Data.items[i])
274+ else
275+ S.AddObject(TJSONObject(Data).Names[i],Data.items[i]);
276+ if FSortObjectMembers and (Data.JSONType=jtObject) then
277+ S.Sort;
278+ for I:=0 to S.Count-1 do
279+ begin
280+ N2:=TVJSON.Items.AddChild(N,S[i]);
281+ D:=TJSONData(S.Objects[i]);
282+ N2.ImageIndex:=ImageTypeMap[D.JSONType];
283+ N2.SelectedIndex:=ImageTypeMap[D.JSONType];
284+ ShowJSONData(N2,D);
285+ end
286+ finally
287+ S.Free;
288+ end;
289+ end;
290+ jtNull:
291+ N:=TVJSON.Items.AddChild(AParent,SNull);
292+ else
293+ N:=TVJSON.Items.AddChild(AParent,Data.AsString);
294+ end;
295+ if Assigned(N) then
296+ begin
297+ N.ImageIndex:=ImageTypeMap[Data.JSONType];
298+ N.SelectedIndex:=ImageTypeMap[Data.JSONType];
299+ N.Data:=Data;
300+ end;
301+ end;
302+end;
303+```
304+
305+## FpcTwit
306+
307+Biblioteka [[Components and Code examples|Przykłady komponentów i kodu]] wykorzystuje JSON do wysyłania/odbierania danych.
308+
309+## Zobacz też
310+
311+- Artykuł dotyczący użycia XML i JSON we FreePascalu: [PDF](http://www.freepascal.org/~michael/articles/webdata/webdata.pdf)
312+- [[Package List|Lista pakietów]]
313+
314+---
315+*From the Free Pascal wiki, page "fcl-json/pl", as it stood on 2021-08-10 after a change by Slawek, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history