Friday, May 2, 2014

Como trabajo con JSON en Delphi?

Para trabajar en JSON se utiliza el objeto TJSONObject, de la siguiente manera:

Si uno está generando la información a enviar puede usar el siguiente método:

var
  LJSONObject: TJSONObject;
 
begin
  LJSONObject:= TJSONObject.Create;
  LJSONObject.AddPair(TJSONPair.Create(TJSONString.Create('Hola'),
                                       TJSONString.Create('Mundo')));

Rápido y sencillo verdad?
Pero digamos que tenemos que utilizar un header predefinido como éste:

const
  GJSONString =
'{'+
    '"glossary": {'+
        '"title": "example glossary",'+
  '"GlossDiv": {'+
            '"title": "S",'+
   '"GlossList": {'+
                '"GlossEntry": {'+
                   ' "ID": "SGML",'+
     '"SortAs": "SGML",'+
     '"GlossTerm": "Standard Generalized Markup Language",'+
     '"Acronym": "SGML",'+
     '"Abbrev": "ISO 8879:1986",'+
     '"GlossDef": {'+
                        '"para": "A meta-markup language, used to create markup languages such as DocBook.",'+
      '"GlossSeeAlso": ["GML", "XML"]'+
                    '},'+
     '"GlossSee": "markup"'+
                '}'+
            '}'+
        '}'+
    '}'+
'}';

Entonces se utiliza la funcion parser del objeto TJSONObject de ésta manera:

procedure ConsumeJsonBytes;
var
  LJSONObject: TJSONObject;
 
begin
  LJSONObject := nil;
  try
    LJSONObject := TJsonObject.Create;
    { convert String to JSON }
    LJSONObject.Parse(BytesOf(GJSONString), 0);
 
    { output the JSON to console as String }
    Writeln(LJSONObject.ToString);
  finally
    LJSONObject.Free;
  end;
end;

Produciendo el objeto deseado.


1 comment:

Exploring the Differences between Red-Teaming and Blue-Teaming in Cybersecurity: Why Red-Teaming is Sexier; but Blue-Teaming is More Crucial

When it comes to cybersecurity, there are two teams that often get confused: redteams and blueteams. Redteams are the hackers, the ones w...