Club Delphi  
    FTP   CCD     Buscar   Trucos   Trabajo   Foros

Retroceder   Foros Club Delphi > Principal > Desarrollo en Delphi para Android
Registrarse FAQ Miembros Calendario Guía de estilo Temas de Hoy


Respuesta
 
Herramientas Buscar en Tema Desplegado
  #1  
Antiguo Hace 1 Día
jmbarrio jmbarrio is offline
Miembro
 
Registrado: may 2003
Posts: 72
Poder: 22
jmbarrio Va por buen camino
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.
Responder Con Cita
  #2  
Antiguo Hace 1 Día
cloayza cloayza is offline
Miembro
 
Registrado: may 2003
Ubicación: San Pedro de la Paz, Chile
Posts: 914
Poder: 23
cloayza Tiene un aura espectacularcloayza Tiene un aura espectacular
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
Responder Con Cita
  #3  
Antiguo Hace 1 Día
jmbarrio jmbarrio is offline
Miembro
 
Registrado: may 2003
Posts: 72
Poder: 22
jmbarrio Va por buen camino
Buenos días, muchas gracias por tu tiempo, lo voy a probar y te digo.

Un saludo
Responder Con Cita
  #4  
Antiguo Hace 1 Día
jmbarrio jmbarrio is offline
Miembro
 
Registrado: may 2003
Posts: 72
Poder: 22
jmbarrio Va por buen camino
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.
Responder Con Cita
Respuesta



Normas de Publicación
no Puedes crear nuevos temas
no Puedes responder a temas
no Puedes adjuntar archivos
no Puedes editar tus mensajes

El código vB está habilitado
Las caritas están habilitado
Código [IMG] está habilitado
Código HTML está deshabilitado
Saltar a Foro

Temas Similares
Tema Autor Foro Respuestas Último mensaje
Problemas con JSON y Tabla de Memoria jmbarrio Delphi para la web 3 Hace 4 Semanas 00:18:28
JSON en Lazarus Punzo Lazarus, FreePascal, Kylix, etc. 5 23-09-2020 21:31:54
Problemas al escribir en un archivo aguml C++ Builder 1 09-01-2018 23:32:54
Problemas al escribir en el Registro de Windows cuando el usuario tiene restricciones JoAnCa Varios 4 07-04-2009 20:36:22
Problemas al escribir el registro de windows pablopessoa Varios 8 17-02-2009 02:35:13


La franja horaria es GMT +2. Ahora son las 12:39:04.


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
Copyright 1996-2007 Club Delphi