Manipularea structurilor JSON folosind biblioteca SuperObject

sintaxa JSON pentru transferul de date

Continut articol

Articolul reprezinta traducerea unui articol similar, care incorporeaza majoritatea explicatiilor necesare pentru utilizarea bibliotecii open source ultra-rapide JSON SuperObject. Informatiile sunt utile programatorilor care utilizeaza platforma de dezvoltare Delphi si doresc sa se conecteze usor la o retea de magazine operata cu SmartCash RMS.

SuperObject – A fast Delphi JSON parser

Puteti descarca sursele componentelor SuperObject pentru Delphi de la urmatoarea adresa: https://code.google.com/p/superobject/downloads/list

JSON (JavaScript Object Notation) reprezinta un format usor si extrem de rapid pentru schimbul de date. Printre caracteristicile sale se numara:

  • Usor de citit de catre operatori umani.
  • Usor de parsat si generat pentru masini.
  • Mult mai compact decat formatul XML.
  • Bazat pe un subset Java Script.
  • Formatul de text este complet independent de limbajul de programare.
  • Foloseste conventii familiare programatorilor.

Toate aceste caracteristici fac din JSON formatul ideal pentru transferul de date intre sisteme informatice, fiind considerat de marea majoritate a programatorilor ca formatul viitorului. Toate sistemele actuale web 2.0, de la Google la Facebook isi bazeaza schimbul de date pe noi API-uri, mult mai rapide, ce au renuntat la formatul XML in favoarea JSON.

JSON este formatul utilizat pentru schimbul de date cu sisteme externe si de platforma SmartCash RMS dezvoltata de Magister Software, prin intermediul componentei specializate SmartCash Everywhere REST Server.

Pentru informatii detaliate legate de JSON puteti consulta: http://www.json.org

Exemple JSON

{
 "name": "John Smith", /* this is a comment */
 "tel": ["555-2345", "0735552345"],
 "age": 18,
 "height": 1.8,
 "place": [{"address": "PO Box 1234", "city": "Florida", "code": 2000},
 {"address": "1 Sparrow street", "city": "Florida", "code": 2000}]
 }

Parsarea unei structuri JSON folosind SuperObject

var
 obj: ISuperObject;
 begin
  obj := SO('{"foo": true}');
  obj := TSuperObject.ParseString('{"foo": true}');
  obj := TSuperObject.ParseStream(stream, true);
  obj := TSuperObject.ParseFile(FileName, true);
 end;

Accesarea datelor

Nu exista structuri individuale pentru fiecare tip de data suportata. Toate sunt definite ca un obiect: ISuperObject.

val := obj.AsString;
val := obj.AsInteger;
val := obj.AsBoolean;
val := obj.AsDouble;
val := obj.AsCurrency;
val := obj.AsArray;
val := obj.AsObject;
val := obj.AsMethod;

Cum se citeste valoarea unei proprietati apartinand unui obiect

val := obj.AsObject.S['foo']; // get a string
val := obj.AsObject.I['foo']; // get an Int64
val := obj.AsObject.B['foo']; // get a Boolean
val := obj.AsObject.D['foo']; // get a Double
val := obj.AsObject.C['foo']; // get a Currency
val := obj.AsObject.O['foo']; // get an Object (default)
val := obj.AsObject.M['foo']; // get a Method
val := obj.AsObject.N['foo']; // get a null object

Cum se citeste o valoare dintr-un array (metoda avansata)

val := obj.AsArray.S[0]; // get a string
val := obj.AsArray.I[0]; // get an Int64
val := obj.AsArray.B[0]; // get a Boolean
val := obj.AsArray.D[0]; // get a Double
val := obj.AsArray.O[0]; // get an Object (default)
val := obj.AsArray.M[0]; // get a Method
val := obj.AsArray.N[0]; // get a null object

Folosirea unei cai (Path)

Folosirea caii este o metoda productiva de a gasi un obiect in cadrul unei structuri JSON atunci cand se cunoaste dinainte structura generala.

Iata in continuare cateva scenarii de utilizare:

 obj['foo']; // get a property
 obj['123']; // get an item array
 obj['foo.list']; // get a property from an object
 obj['foo[123]']; // get an item array from an object
 obj['foo(1,2,3)']; // call a method
 obj['foo[]'] := value; // add an item array

Caile pot fi si incapsulate la scriere:

obj := SO('{"index": 1, "items": ["item 1", "item 2", "item 3"]}');
obj['items[index]'] // return "item 2"

sau se poate recrea o structura din alta:

obj := SO('{"index": 1, "items": ["item 1", "item 2", "item 3"]}');
obj['{"item": items[index], "index": index}']; // return {"item": "item 2", "index": 1}

Browsing pe structura de date folosind enumerarea Delphi

Folosind enumerarea Delphi puteti face browse pe articolele unui array sau pe valorile proprietatilor unui obiect.

var
 item: ISuperObject;
 begin
 for item in obj['items'] do...

de asemenea pe cheile si valorile lor dintr-un obiect astfel:

var
 item: TSuperAvlEntry;
 begin
 for item in obj.AsObject do begin
  item.Name;
  item.Value;
 end;...

Browsing pe proprietatile unui obiect fara enumerator

var
 item: TSuperObjectIter;
 begin
  if ObjectFindFirst(obj, item) then
   repeat
    item.key;
    item.val;
   until not ObjectFindNext(item);
 ObjectFindClose(item);...

Browsing pe item-urile unui array fara enumerator

var
 item: Integer;
 begin
  for item := 0 to obj.AsArray.Length - 1 do
 obj.AsArray[item]...

Salvarea datelor

  obj.AsJSon(options);
  obj.SaveTo(stream);
  obj.SaveTo(filename);

Exemplu de cod de pe forumul SuperObject

procedure TForm1.Button1Click(Sender: TObject);
var
obj: ISuperObject;
t: ISuperObject;
begin
 obj := SO();
 // add a couple of named values
 obj['something'] := SO(255);
 obj['else'] := SO('bunyips');

 // add an array
 t := SA([]);
 t['[0]'] := SO('something');
 t['[1]'] := SO('else');
 t['[2]'] := SO(3);
 obj['AnArray'] := t;

// or if you know what sort of values your adding....
 t := SA([]);
 t.AsArray.I[0] := 64;
 t.AsArray.I[1] := 32;
 t.AsArray.S[2] := 'some string';
 obj['AnotherArray'] := t;

 // or another way......
 t := SA([]);
 t.AsArray[0] := SO(64);
 t.AsArray[1] := SO(32);
 t.AsArray[2] := SO('some string');
 obj['SimplerArray'] := t;

 // add another object into the object
 t := SO();
 t['somevalue'] := SO('bleh');
 t['anArrayAgain'] := SA([1,2,'three']); // notice the way this array was created
 obj['anotherObject'] := t;

 // use the path to add the same object in deeper
 obj['in.real.deep'] := t;
 memo1.text := obj.AsJSon();
 obj.SaveTo('noname.json');
end;