Generate JSON Delphi 7 file

2

I need to generate a JSON file with Delphi 7. I use the LKJSON library.

I even managed to generate the file, but it was not the way I would need it.

Below the code I used to generate JSON:

procedure TForm1.Button3Click(Sender: TObject);
var
  js: TlkJSONobject;
  s: string;
  i : Integer;

begin

  SQLConnection1.Open;
  taUF.Open;

  js := TlkJSONobject.Create;

  try

    js.Add('estado', TlkJSONobject.Create);

    taUF.First;
    while not taUF.Eof do begin

      with TlkJSONobject(TlkJSONobject(js['estado'])) do begin
        Add('sigla', taUF.FieldByName('UFSigla').AsString);
        Add('nome', taUF.FieldByName('UFNome').AsString);
      end;

      taUF.Next;

    end;//while

    i := 0;
    s := GenerateReadableText(js, i);
    Clipboard.SetTextBuf(PChar(s));

  finally
    js.Free;
  end;

end;

This is the result:

{
  "estado":{
    "sigla":"RJ",
    "nome":"RIO DE JANEIRO",
    "sigla":"SC",
    "nome":"SANTA CATARINA"
  }
}

I need it to look this way:

{
  "estado":
    {
    "sigla":"RJ",
    "nome":"RIO DE JANEIRO"
    },
    {"sigla":"SC",
    "nome":"SANTA CATARINA"
    }
}
    
asked by anonymous 23.08.2016 / 16:36

1 answer

-1

As mentioned in the comments, you will have to work with lists to generate the JSON, follow a code as an example:

procedure TForm2.Button1Click(Sender: TObject);
var
  JsonFull: TlkJSONobject;
  PropertyJson: TlkJSONobject;
  JsonList: TlkJSONlist;
  s: string;
  i: Integer;

begin
  JsonFull := TlkJSONobject.Create;
  JsonList := TlkJSONlist.Create;

  try
    for i := 1 to 5 do
    begin
      PropertyJson := TlkJSONobject.Create;
      PropertyJson.Add('sigla', 'UF' + IntToStr(i));
      PropertyJson.Add('nome', 'Estado' + IntToStr(i));
      JsonList.Add(PropertyJson);

    end;

    JsonFull.Add('estado', JsonList);

    i := 0;
    s := GenerateReadableText(JsonFull, i);
    Clipboard.SetTextBuf(PChar(s));

  finally
    FreeAndNil(JsonFull);
  end;

end;

3 new Variables have been created:

JsonFull: TlkJSONobject - Which represents JSON with list of objects

PropertyJson: TlkJSONobject - Which represents each State

JsonList: TlkJSONlist - Which represents the list with states

With this, each object will belong to the other, like a cascade:

PropertyJson.Add(Estado) > JsonList.Add(PropertyJson) > JsonFull.Add(JsonList)
    
23.08.2016 / 21:32