Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Varios (https://www.clubdelphi.com/foros/forumdisplay.php?f=11)
-   -   Obtener campo usando REST (https://www.clubdelphi.com/foros/showthread.php?t=92353)

MAXIUM 06-10-2017 05:35:36

Obtener campo usando REST
 
Usando los componentes de REST y JSON en Delphi 10, ¿como puedo mostrar los datos en Label?

Ejemplo:

Cita:

"Usuario":{
"id":"1",
"nombre":"Galvin",
"apellidos":"Davenport, Thomas T.",
"telefono":"06 09 69 ",
"extension":"7645",
"departamento":"Nibh Quisque As",
"interno":"165",
"email":"laoreet@antedictum.org"
}
Quiero que el valor del campo "nombre" se muestre por medio de un Label.

Y como segunda pregunta, ¿Como puedo mostrar estos valores en una StringGrid y no en una DBGrid?. De antemano, gracias.

Cita:

{
"Usuarios":[
{
"Usuario":{
"id":"1",
"nombre":"Galvin",
"apellidos":"Davenport, Thomas T.",
"telefono":"06 09 69 ",
"extension":"7645",
"departamento":"Nibh Quisque As",
"interno":"165",
"email":"laoreet@antedictum.org"
}
},
{
"Usuario":{
"id":"2",
"nombre":"Ferdinand",
"apellidos":"Adams, Arthur N.",
"telefono":"08 61 65 ",
"extension":"9370",
"departamento":"Sed Consulting",
"interno":"212",
"email":"diam.luctus.lobortis@augueSed.edu"
}
},
{
"Usuario":{
"id":"3",
"nombre":"Ira",
"apellidos":"Mayo, Solomon G.",
"telefono":"03 26 35 ",
"extension":"5479",
"departamento":"Eget Inc.",
"interno":"697",
"email":"nec@commodohendrerit.com"
}
},
{
"Usuario":{
"id":"4",
"nombre":"Stuart",
"apellidos":"Ramsey, Ivana X.",
"telefono":"09 40 92 ",
"extension":"6342",
"departamento":"In Corporation",
"interno":"251",
"email":"dui.semper@nisidictumaugue.net"
}
},
{
"Usuario":{
"id":"5",
"nombre":"Bruce",
"apellidos":"Francis, Medge X.",
"telefono":"08 02 80 ",
"extension":"1043",
"departamento":"Turpis Nec Comp",
"interno":"532",
"email":"nunc.Quisque@rutrum.net"
}
},
{
"Usuario":{
"id":"6",
"nombre":"Nolan",
"apellidos":"Russell, Winter O.",
"telefono":"03 92 73 ",
"extension":"9689",
"departamento":"Malesuada Males",
"interno":"109",
"email":"leo@semper.net"
}
},
{
"Usuario":{
"id":"7",
"nombre":"Leroy",
"apellidos":"Ortega, Mariko T.",
"telefono":"02 21 38 ",
"extension":"9999",
"departamento":"Urna Nunc Quis ",
"interno":"954",
"email":"lorem@consequatpurusMaecenas.com"
}
},
{
"Usuario":{
"id":"8",
"nombre":"Keith",
"apellidos":"Byrd, Martena Q.",
"telefono":"07 89 67 ",
"extension":"6728",
"departamento":"Vel Vulputate L",
"interno":"988",
"email":"diam.dictum.sapien@Vivamusrhoncus.net"
}
},
{
"Usuario":{
"id":"9",
"nombre":"Ferdinand",
"apellidos":"Warner, Gillian M.",
"telefono":"09 87 76 ",
"extension":"2426",
"departamento":"Suspendisse Ali",
"interno":"380",
"email":"Aliquam.adipiscing.lobortis@acrisusMorbi"
}
},
{
"Usuario":{
"id":"10",
"nombre":"Kasper",
"apellidos":"Chapman, Veronica D.",
"telefono":"05 05 24 ",
"extension":"1125",
"departamento":"Purus Incorpora",
"interno":"397",
"email":"et.netus@sapien.ca"
}
}
]
}

mallenat 06-10-2017 08:20:58

¿Has visto el ejemplo de la web de embarcadero?

Puedes usar Live Bindings o directamente leer de un objeto TJSONObject usando el metodo GetValue. Ejemplo
Código Delphi [-]
jValue := jObject.GetValue('nombre');

Neftali [Germán.Estévez] 06-10-2017 12:13:28

1 Archivos Adjunto(s)
Si vas a trabajar mucho con estar estructura (y también para mantener un código limpio), vale la pena utilizar esta herramienta de la que ya he hablado en el blog.

JsonToDelphiClass

Permite como su nombre indica, generar una unit con las clases necesarias para trabajar con el JSON que le proporciones.
Si la generas para este JSON obtendrás el fichero que te adjunto.

La gracias es que con una línea como esta puedes cargar todo el JSON es un objeto.

Código Delphi [-]
var  
  ULista:TListaUsuarios;
begin
  // si en el memo tenemos el JSON...
  ULista := TListaUsuarios.FromJsonString(Memo1.Lines.Text);
  
  // ...

A partir de este punto, en ULista tienes todo el JSON.
Para recorrerlo y acceder a los elementos puedes utilizar algo así (o para guardarlos en un TSTringGrid):

Código Delphi [-]
procedure TForm2.FormShow(Sender: TObject);
var
  nUsuarios:integer;
  i:integer;
  us:TUsuariosClass;
begin

  ULista := TListaUsuarios.FromJsonString(Memo1.Lines.Text);
  nUsuarios := Length(ULista.Usuarios);

  // Lineas
  SG.RowCount := nUsuarios + 1;
  // Titulos
  SG.Cells[0, 0] := 'Id';
  SG.Cells[1, 0] := 'Nombre';
  SG.Cells[2, 0] := 'Apellidos';
  //.. resto de columnas

  // Cargar usuarios en un StringGrid
  for i := 0 to (nUsuarios - 1) do begin
    us := ULista.Usuarios[i];
    SG.Cells[0, i+1] := us.Usuario.id;
    SG.Cells[1, i+1] := us.Usuario.nombre;
    SG.Cells[2, i+1] := us.Usuario.apellidos;
    // resto de columnas
  end;
end;

MAXIUM 07-10-2017 05:45:20

Neftali, maravilloso el JsonToDelphiClass. Hasta tiene una versión online https://jsontodelphi.com Me facilito la vida.

Aprendiendo este submundo. Gracias ^\||/

lbidi 10-08-2018 22:05:29

Hola neftali .. muchas gracias por compartir ese codigo y el sitio para crear esas clases. Es fantastico.

Ahora te pido una ayuda para comprender como "leer" los objetos de dicha clase con este Json

[
{
"id": 71,
"companyId": 4,
"name": "Leo b",
"email": null,
"takeAway": false,
"deviceId": 457,
"state": "NEW",
"dateNew": 1533517288534,
"street": "Mac eachen",
"total": 332,
"number": "1324",
"betweenStreet": "",
"apartmentNumber": "",
"telephone": "099127695",
"annotation": null,
"products": [
{
"comment": null,
"code": 709,
"amount": 2,
"name": "PIZZETA A LA SALSA",
"total": 185,
"productItemsName": []
}
],
"dateInitProcess": null,
"timeToFinishProcess": null,
"dateFinish": null,
"dateCancel": null,
"cancelBecause": null
},
{
"id": 70,
"companyId": 4,
"name": "Leo b",
"email": null,
"takeAway": false,
"deviceId": 457,
"state": "NEW",
"dateNew": 1533517256850,
"street": "Mac eachen",
"total": 170,
"number": "1324",
"betweenStreet": "",
"apartmentNumber": "",
"telephone": "099127695",
"annotation": null,
"products": [
{
"comment": null,
"code": 102,
"amount": 1,
"name": "PIZZA",
"total": 75,
"productItemsName": []
},
{
"comment": null,
"code": 101,
"amount": 1,
"name": "MUZZARELLA",
"total": 115,
"productItemsName": []
}
],
"dateInitProcess": null,
"timeToFinishProcess": null,
"dateFinish": null,
"dateCancel": null,
"cancelBecause": null
},
]

Me ha definido esta clase pero no me doy cuenta como utilizarla. Muchas gracias desde ya !!!!

Código Delphi [-]
unit JSonClass;

{*******************************************************************************
    Generated By   : JsonToDelphiClass - 0.65 
    Project link   : https://github.com/PKGeorgiev/Delphi-JsonToDelphiClass
    Generated On   : 2018-08-10 16:24:40

    Created By     : Petar Georgiev - (http://pgeorgiev.com) 
    Adapted Web By : Marlon Nardi - (http://jsontodelphi.com)
*******************************************************************************}

interface

uses Generics.Collections, Rest.Json;

type

TProductItemsNameClass = class
private
public
  function ToJsonString: string;
  class function FromJsonString(AJsonString: string): TProductItemsNameClass;
end;

TProductsClass = class
private
  FAmount: Extended;
  FCode: Extended;
  FName: String;
  FProductItemsName: TArray;
  FTotal: Extended;
public
  property amount: Extended read FAmount write FAmount;
  property code: Extended read FCode write FCode;
  property name: String read FName write FName;
  property productItemsName: TArray read FProductItemsName write FProductItemsName;
  property total: Extended read FTotal write FTotal;
  destructor Destroy; override;
  function ToJsonString: string;
  class function FromJsonString(AJsonString: string): TProductsClass;
end;

TItemClass = class
private
  FApartmentNumber: String;
  FBetweenStreet: String;
  FCompanyId: Extended;
  FDateNew: Extended;
  FDeviceId: Extended;
  FId: Extended;
  FName: String;
  FNumber: String;
  FProducts: TArray;
  FState: String;
  FStreet: String;
  FTakeAway: Boolean;
  FTelephone: String;
  FTotal: Extended;
public
  property apartmentNumber: String read FApartmentNumber write FApartmentNumber;
  property betweenStreet: String read FBetweenStreet write FBetweenStreet;
  property companyId: Extended read FCompanyId write FCompanyId;
  property dateNew: Extended read FDateNew write FDateNew;
  property deviceId: Extended read FDeviceId write FDeviceId;
  property id: Extended read FId write FId;
  property name: String read FName write FName;
  property number: String read FNumber write FNumber;
  property products: TArray read FProducts write FProducts;
  property state: String read FState write FState;
  property street: String read FStreet write FStreet;
  property takeAway: Boolean read FTakeAway write FTakeAway;
  property telephone: String read FTelephone write FTelephone;
  property total: Extended read FTotal write FTotal;
  destructor Destroy; override;
  function ToJsonString: string;
  class function FromJsonString(AJsonString: string): TItemClass;
end;

TRootClass = class
private
  FItems: TArray;
public
  property Items: TArray read FItems write FItems;
  destructor Destroy; override;
  function ToJsonString: string;
  class function FromJsonString(AJsonString: string): TRootClass;
end;

implementation

{TProductItemsNameClass}

function TProductItemsNameClass.ToJsonString: string;
begin
  result := TJson.ObjectToJsonString(self);
end;

class function TProductItemsNameClass.FromJsonString(AJsonString: string): TProductItemsNameClass;
begin
  result := TJson.JsonToObject(AJsonString)
end;

{TProductsClass}

destructor TProductsClass.Destroy;
var
  LproductItemsNameItem: TProductItemsNameClass;
begin

 for LproductItemsNameItem in FProductItemsName do
   LproductItemsNameItem.Free;

  inherited;
end;

function TProductsClass.ToJsonString: string;
begin
  result := TJson.ObjectToJsonString(self);
end;

class function TProductsClass.FromJsonString(AJsonString: string): TProductsClass;
begin
  result := TJson.JsonToObject(AJsonString)
end;

{TItemClass}

destructor TItemClass.Destroy;
var
  LproductsItem: TProductsClass;
begin

 for LproductsItem in FProducts do
   LproductsItem.Free;

  inherited;
end;

function TItemClass.ToJsonString: string;
begin
  result := TJson.ObjectToJsonString(self);
end;

class function TItemClass.FromJsonString(AJsonString: string): TItemClass;
begin
  result := TJson.JsonToObject(AJsonString)
end;

{TRootClass}

destructor TRootClass.Destroy;
var
  LItemsItem: TItemClass;
begin

 for LItemsItem in FItems do
   LItemsItem.Free;

  inherited;
end;

function TRootClass.ToJsonString: string;
begin
  result := TJson.ObjectToJsonString(self);
end;

class function TRootClass.FromJsonString(AJsonString: string): TRootClass;
begin
  result := TJson.JsonToObject(AJsonString)
end;

end.

lbidi 13-08-2018 21:53:52

Hola foristas..

Alguien que me ayude a entender como interpretar esa clase para poder obtener datos del json que menciono ??

Muchas gracias !!

lbidi 30-08-2018 17:06:35

Hola.. alguien que me ayude con esta clase ?? No se como implementarla y llamarla..

Muchas gracias !!!

Neftali [Germán.Estévez] 31-08-2018 08:36:02

Hola.
Revisa que el JSON que has colocado esté bien (si hace falta utiliza etiquetes para que la web no elimine caracteres).
Tal y como está no me deja generar la clase.

Para utilizarla, puedes usar un código similar a este.

Siempre se empieza utilizando la función FromJsonString. En tu caso la de la clase TProductsClass.

lbidi 31-08-2018 16:15:41

Gracias German, hace dias que estoy tratando de "interpretar" el json con esa clase, pero mis conocimientos de clases son minimos..

el json que deseo analizar es este..
Código Delphi [-]
[
  {
    "id": 97,
    "companyId": 4,
    "name": "Leo",
    "email": null,
    "takeAway": false,
    "deviceId": 567,
    "state": "NEW",
    "dateNew": 1534989003909,
    "branchId": 4,
    "paymentMethod": "CASH",
    "tableNumber": null,
    "street": "Mac Eachen ",
    "total": 166,
    "number": "1324",
    "betweenStreet": "Payan",
    "apartmentNumber": "",
    "telephone": "099127695",
    "annotation": null,
    "products": [
      {
        "comment": null,
        "code": 709,
        "amount": 1,
        "name": "A la Salsa",
        "total": 185,
        "productItemsName": [{}]
      }
    ],
    "dateInitProcess": null,
    "timeToFinishProcess": null,
    "dateFinish": null,
    "dateCancel": null,
    "cancelBecause": null,
    "branchVO": {
      "id": 4,
      "version": null,
      "name": "Sucursal Principal",
      "description": "Sucursal Principal",
      "contact": {
        "firstEmail": null,
        "secondEmail": null,
        "firstPhone": null,
        "secondPhone": null,
        "firstCellPhone": null,
        "secondCellPhone": null
      },
      "coordinates": {
        "latitude": 1,
        "longitude": 1
      },
      "address": {
        "departament": "Montevideo",
        "city": "Montevideo",
        "street": "Br. Artigas 20001",
        "portNumber": "1",
        "bis": true,
        "apartment": "N/A"
      },
      "removed": false,
      "principal": true,
      "companyId": 4
    }
  },
  {
    "id": 96,
    "companyId": 4,
    "name": "Leo",
    "email": null,
    "takeAway": false,
    "deviceId": 567,
    "state": "NEW",
    "dateNew": 1534988959009,
    "branchId": 4,
    "paymentMethod": "CASH",
    "tableNumber": null,
    "street": "Mac Eachen ",
    "total": 175,
    "number": "1324",
    "betweenStreet": "Payan",
    "apartmentNumber": "",
    "telephone": "099127695",
    "annotation": null,
    "products": [
      {
        "comment": null,
        "code": 105,
        "amount": 1,
        "name": "Pizza con gustos",
        "total": 120,
        "productItemsName": [
          "Cebolla",
          "Jamón"
        ]
      },
      {
        "comment": null,
        "code": 102,
        "amount": 1,
        "name": "Pizza",
        "total": 75,
        "productItemsName": [{}]
      }
    ],
    "dateInitProcess": null,
    "timeToFinishProcess": null,
    "dateFinish": null,
    "dateCancel": null,
    "cancelBecause": null,
    "branchVO": {
      "id": 4,
      "version": null,
      "name": "Sucursal Principal",
      "description": "Sucursal Principal",
      "contact": {
        "firstEmail": null,
        "secondEmail": null,
        "firstPhone": null,
        "secondPhone": null,
        "firstCellPhone": null,
        "secondCellPhone": null
      },
      "coordinates": {
        "latitude": 1,
        "longitude": 1
      },
      "address": {
        "departament": "Montevideo",
        "city": "Montevideo",
        "street": "Br. Artigas 20001",
        "portNumber": "1",
        "bis": true,
        "apartment": "N/A"
      },
      "removed": false,
      "principal": true,
      "companyId": 4
    }
  }
]

He testeado este json en la pagina de jsontodelphi y me genera la clase, mi problema es que no se luego como utilizarla.

Ademas he mirado el post que mencionas, pero no le he comprendido del todo. :(..

Mil gracias por tu invalorable ayuda..


La franja horaria es GMT +2. Ahora son las 21:48:35.

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