Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Desarrollo en Delphi para Android (https://www.clubdelphi.com/foros/forumdisplay.php?f=57)
-   -   Problemas al escribir JSON (https://www.clubdelphi.com/foros/showthread.php?t=96700)

jmbarrio 14-05-2024 16:46:10

Problemas al escribir JSON
 
Buenas tardes, tengo el siguiente código para montar un archivo Json

Código Delphi [-]
procedure TF_Inicio.btFacturaRapidaClick(Sender: TObject);
var
  MainObject, lJNestedObject, lJRestoredObject, ObjArticu, ObjLinea: TJSONObject;
  Array_Articu,Array_Linea: TJSONArray;

begin

  try
    // Veo las facturas que están pendientes de enviar
    sqlstr := 'Select * from facemi where fae_entregado = ' + '''' + 'N' + '''';
      with F_Data.FDQry do
        begin
          Sql.Clear;
          Active := False;
          Sql.Add(sqlstr);
          Active := True;
          Open;
          Memo1.Visible := True;
          Memo1.Lines.Clear;

          MainObject := TJSONObject.Create;
          Array_Articu := TJSONArray.Create;
          MainObject.AddPair(TJSONPair.Create('facemi', Array_Articu));

          First;
          while not eof do
            begin
              ObjArticu := TJSONObject.Create;
              ObjArticu.AddPair(TJSONPair.Create('fae_serie',FieldByName('FAE_SERIE').AsString));
              ObjArticu.AddPair(TJSONPair.Create('fae_nro',FieldByName('FAE_NRO').AsInteger));
              Array_Articu.Add(ObjArticu);
              sqlstr := 'Select * from lifacl where lfa_serie = ' + '''' + FieldByName('FAE_SERIE').AsString + '''' + ' and lfa_fnro = ' +
                        FieldByName('FAE_NRO').AsInteger.ToString + ' order by lfa_linea asc';
              with F_Data.FDQry1 do
                begin
                  Sql.Clear;
                  Active := False;
                  Sql.Add(sqlstr);
                  Active := True;
                  Open;
                  First;
                  Array_Linea := TJSONArray.Create;
                  while not eof  do
                    begin
                      ObjLinea := TJSONObject.Create;
                      ObjLinea.AddPair(TJSONPair.Create('lfa_serie',FieldByName('LFA_SERIE').AsString));
                      ObjLinea.AddPair(TJSONPair.Create('lfa_fnro',FieldByName('LFA_FNRO').AsInteger));
                      ObjLinea.AddPair(TJSONPair.Create('lfa_linea',FieldByName('LFA_LINEA').AsInteger));
                      Array_Linea.Add(ObjLinea);
                      Next;
                    end;
                  ObjArticu.AddPair(TJSONPair.Create('lifacl', Array_Linea ) ) ;
                end;
              Next;
            end;

          Memo1.Text := MainObject.ToJSON;
          Memo1.Text := copy(Memo1.Text,11, length(Memo1.Text)-11);

          {$IF DEFINED (WIN32) or DEFINED (WIN64)}
            TFile.WriteAllText('jsonfile.json', '[' + MainObject.Format() + ']'); //Solo para windows
          {$ENDIF}

          RestClient3.BaseURL := servidorWS + 'Facemi/Importar';
          RestRequest3.ClearBody;  //Si no se pone solo se puede ejecutar el post una sola vez
          RestRequest3.Body.Add(MainObject.Format(),TRestContentType.ctAPPLICATION_JSON);
          //RestRequest3.Body.Add(Memo1.Text,TRestContentType.ctAPPLICATION_JSON);
          RestRequest3.Execute;

          MainObject.Free;
        end;
  except
    on e: exception do
      showmessage(e.Message);
  end;
end;

El cual me genera el archivo json

Código:

[{
    "facemi": [
        {
            "fae_serie": "AA",
            "fae_nro": 28,
            "lifacl": [
                {
                    "lfa_serie": "AA",
                    "lfa_fnro": 28,
                    "lfa_linea": 1
                },
                {
                    "lfa_serie": "AA",
                    "lfa_fnro": 28,
                    "lfa_linea": 2
                },
                {
                    "lfa_serie": "AA",
                    "lfa_fnro": 28,
                    "lfa_linea": 3
                }
            ]
        },
        {
            "fae_serie": "AA",
            "fae_nro": 29,
            "lifacl": [
                {
                    "lfa_serie": "AA",
                    "lfa_fnro": 29,
                    "lfa_linea": 1
                },
                {
                    "lfa_serie": "AA",
                    "lfa_fnro": 29,
                    "lfa_linea": 2
                }
            ]
        }
    ]
}]

El problema que tengo es que el endpoint no me coge esa esctructura, necesito que el Json tenga la siguiente estructura, pero no se como hacerlo no doy con la tecla.

Código:

[
        {
            "fae_serie": "AA",
            "fae_nro": 28,
            "lifacl": [
                {
                    "lfa_serie": "AA",
                    "lfa_fnro": 28,
                    "lfa_linea": 1
                },
                {
                    "lfa_serie": "AA",
                    "lfa_fnro": 28,
                    "lfa_linea": 2
                },
                {
                    "lfa_serie": "AA",
                    "lfa_fnro": 28,
                    "lfa_linea": 3
                }
            ]
        },
        {
            "fae_serie": "AA",
            "fae_nro": 29,
            "lifacl": [
                {
                    "lfa_serie": "AA",
                    "lfa_fnro": 29,
                    "lfa_linea": 1
                },
                {
                    "lfa_serie": "AA",
                    "lfa_fnro": 29,
                    "lfa_linea": 2
                }
            ]
        }
]

Muchas gracias de antemano, un saludo.

cloayza 15-05-2024 01:27:37

Estimado me tome la libertad de realizar algunos cambios que creo serán beneficiosos...Si considera que no, los puede desechar.

En mi opinion el código queda mas claro...Bueno eso es una apreciación muy personal...

Código Delphi [-]
procedure TF_Inicio.btFacturaRapidaClick(Sender: TObject);
var
  MainObject, lJNestedObject, lJRestoredObject, ObjArticu, ObjLinea: TJSONObject;
  Array_Articu,Array_Linea: TJSONArray;
begin
  try
    // Veo las facturas que están pendientes de enviar
      Memo1.Visible := True;
      Memo1.Lines.Clear;

      Array_Articu := TJSONArray.Create;
     
      F_Data.FDQry.Active := False;
      F_Data.FDQry.Sql.Clear;
      F_Data.FDQry.Sql.Add('Select * ');
      F_Data.FDQry.Sql.Add('from facemi');
      F_Data.FDQry.Sql.Add('where fae_entregado =:fae_entregado');
      F_Data.FDQry.ParamByName('fae_entregado').AsString:='N';
      F_Data.FDQry.Open;
      F_Data.FDQry.First;
    
      while not F_Data.FDQry.eof do
      begin
           ObjArticu := TJSONObject.Create;
           ObjArticu.AddPair(TJSONPair.Create('fae_serie',F_Data.FDQry.FieldByName('FAE_SERIE').AsString));
           ObjArticu.AddPair(TJSONPair.Create('fae_nro',F_Data.FDQry.FieldByName('FAE_NRO').AsInteger));
              
           F_Data.FDQry1.Active := False;
           F_Data.FDQry1.Sql.Clear;           
           F_Data.FDQry1.Sql.Add('Select * ');
           F_Data.FDQry1.Sql.Add('from lifacl');
           F_Data.FDQry1.Sql.Add('where lfa_serie =:lfa_serie and ');
           F_Data.FDQry1.Sql.Add('      lfa_fnro =:lfa_fnro');
           F_Data.FDQry1.Sql.Add('order by lfa_linea asc');
           F_Data.FDQry1.ParamByName('lfa_serie').AsString:=F_Data.FDQry.FieldByName('FAE_SERIE').AsString;
           ObjArticu.AddPair(TJSONPair.Create('fae_nro',TJSONNumber.Create(FDQry.FieldByName('FAE_NRO').AsInteg  er)));

           F_Data.FDQry1.Open;
           F_Data.FDQry1.First;
           
           Array_Linea := TJSONArray.Create;
          
           while not F_Data.FDQry1.eof  do
           begin
                ObjLinea := TJSONObject.Create;
                ObjLinea.AddPair(TJSONPair.Create('lfa_serie',F_Data.FDQry1.FieldByName('LFA_SERIE').AsString));
                ObjLinea.AddPair(TJSONPair.Create('lfa_fnro',TJSONNumber.Create(FDQry1.FieldByName('LFA_FNRO').AsInt  eger)));
                ObjLinea.AddPair(TJSONPair.Create('lfa_linea',TJSONNumber.Create(FDQry1.FieldByName('LFA_LINEA').AsI  nteger)));
        
                Array_Linea.Add(ObjLinea);
        
                F_Data.FDQry1.Next;
           end;
           ObjArticu.AddPair(TJSONPair.Create('lifacl', Array_Linea ) ) ;

           Array_Articu.Add(ObjArticu);       
       
     F_Data.FDQry.Next;
      end;

          Memo1.Text := Array_Articu.ToJSON;
          Memo1.Text := copy(Memo1.Text,11, length(Memo1.Text)-11);

          {$IF DEFINED (WIN32) or DEFINED (WIN64)}
            TFile.WriteAllText('jsonfile.json', Array_Articu.ToJSON); //Solo para windows
          {$ENDIF}

          RestClient3.BaseURL := servidorWS + 'Facemi/Importar';
          RestRequest3.ClearBody;  //Si no se pone solo se puede ejecutar el post una sola vez
          RestRequest3.Body.Add(Array_Articu.ToJSON,TRestContentType.ctAPPLICATION_JSON);
          //RestRequest3.Body.Add(Memo1.Text,TRestContentType.ctAPPLICATION_JSON);
          RestRequest3.Execute;
  except
    on e: exception do
      showmessage(e.Message);
  end;
end;

Espero que le sea de ayuda u oriente en la solución de su problema....

Saludos cordiales

jmbarrio 15-05-2024 08:55:15

Buenos días, muchas gracias por tu tiempo, lo voy a probar y te digo.

Un saludo

jmbarrio 15-05-2024 09:49:05

Buenos días, he probado tu código y ya me genera el json con la estructura tal y cómo la quiero.

Saludos y muchas gracias.


La franja horaria es GMT +2. Ahora son las 13:20:13.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi