Club Delphi  
    FTP   CCD     Buscar   Trucos   Trabajo   Foros

Retroceder   Foros Club Delphi > Principal > Varios
Registrarse FAQ Miembros Calendario Guía de estilo Buscar Temas de Hoy Marcar Foros Como Leídos

Grupo de Teaming del ClubDelphi

Respuesta
 
Herramientas Buscar en Tema Desplegado
  #1  
Antiguo 06-10-2017
Avatar de MAXIUM
MAXIUM MAXIUM is offline
Miembro
 
Registrado: may 2005
Posts: 1.485
Poder: 20
MAXIUM Va camino a la fama
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"
}
}
]
}
Responder Con Cita
  #2  
Antiguo 06-10-2017
Avatar de mallenat
mallenat mallenat is offline
Miembro
 
Registrado: oct 2003
Posts: 18
Poder: 0
mallenat Va por buen camino
¿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');
__________________
Mallenat
Responder Con Cita
  #3  
Antiguo 06-10-2017
Avatar de Neftali [Germán.Estévez]
Neftali [Germán.Estévez] Neftali [Germán.Estévez] is offline
[becario]
 
Registrado: jul 2004
Ubicación: Barcelona - España
Posts: 18.233
Poder: 10
Neftali [Germán.Estévez] Es un diamante en brutoNeftali [Germán.Estévez] Es un diamante en brutoNeftali [Germán.Estévez] Es un diamante en bruto
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;
Archivos Adjuntos
Tipo de Archivo: zip UTListaUsuariosClass.zip (904 Bytes, 11 visitas)
__________________
Germán Estévez => Web/Blog
Guía de estilo, Guía alternativa
Utiliza TAG's en tus mensajes.
Contactar con el Clubdelphi

P.D: Más tiempo dedicado a la pregunta=Mejores respuestas.

Última edición por Neftali [Germán.Estévez] fecha: 07-10-2017 a las 13:57:30. Razón: Añadr adjunto
Responder Con Cita
  #4  
Antiguo 07-10-2017
Avatar de MAXIUM
MAXIUM MAXIUM is offline
Miembro
 
Registrado: may 2005
Posts: 1.485
Poder: 20
MAXIUM Va camino a la fama
Neftali, maravilloso el JsonToDelphiClass. Hasta tiene una versión online https://jsontodelphi.com Me facilito la vida.

Aprendiendo este submundo. Gracias
Responder Con Cita
  #5  
Antiguo 10-08-2018
Avatar de lbidi
lbidi lbidi is offline
Miembro
 
Registrado: oct 2003
Ubicación: Montevideo- URUGUAY
Posts: 417
Poder: 21
lbidi Va por buen camino
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.
Responder Con Cita
  #6  
Antiguo 13-08-2018
Avatar de lbidi
lbidi lbidi is offline
Miembro
 
Registrado: oct 2003
Ubicación: Montevideo- URUGUAY
Posts: 417
Poder: 21
lbidi Va por buen camino
Hola foristas..

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

Muchas gracias !!
Responder Con Cita
Respuesta


Herramientas Buscar en Tema
Buscar en Tema:

Búsqueda Avanzada
Desplegado

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
Como obtener datos de un servidor rest con autenticacion lbidi Varios 2 20-03-2017 16:41:38
PayPal usando REST oesqueda Delphi para la web 5 02-12-2014 01:36:41
Insertar *.JPG en campo blob usando IBX servicomp Firebird e Interbase 2 22-10-2010 04:27:56
consulta SQL en Delphi 5 usando like en un campo memo MaSSaKKre SQL 4 12-02-2007 02:52:02


La franja horaria es GMT +2. Ahora son las 10:41:02.


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