Método para converter Json para uma lista de Objetos
Obs: Delphi XE6.
Danilo Pereira
Melhor post
Dorivan Sousa
24/06/2015
testa ai amnha a gente v, vai precisar tambem pecorrer os enderecos, cupons e fazendas q pelo que vi sao array q podem trazer mais de um registro
var
Json: WideString;
e, i: integer;
jl: TlkJSONlist;
ja: TlkJSONobject;
begin
try
Json:=Edit1.Text;
if Length(Json) > 0 then
begin
jl := TlkJSON.ParseText(Json) as TlkJSONlist;
if assigned(jl) then
begin
for i:=0 to jl.count-1 do
begin
ja := jl.child[i] as TlkJSONobject; //acho que mudando aqui ja resolveria
pessoa.EmptyDataSet;
pessoa.Append;
pessoacodigo.AsString:=VarToStr(ja.Field['codigo'].Value);
pessoastatus.AsString:=VarToStr(ja.Field['status'].Value);
pessoarazaoSocial.AsString:=VarToStr(ja.Field['razaoSocial'].Value);
pessoaapelidoFantasia.AsString:=VarToStr(ja.Field['apelidoFantasia'].Value);
pessoacnpjCpf.AsString:=VarToStr(ja.Field['cpfCnpj'].Value);
pessoainscEstRg.AsString:=VarToStr(ja.Field['inscEstRg'].Value);
pessoainscMunicipal.AsString:=VarToStr(ja.Field['inscMunicipal'].Value);
pessoafone.AsString:=VarToStr(ja.Field['fone'].Value);
Pessoaendereco.AsString:=VarToStr(ja.Field['endereco'].Field['nomeLogradouro'].Value);
Pessoanumero.AsString:=VarToStr(ja.Field['endereco'].Field['numero'].Value);
Pessoabairro.AsString:=VarToStr(ja.Field['endereco'].Field['bairro'].Value);
Pessoacidade.AsString:=VarToStr(ja.Field['endereco'].Field['cidade'].Value);
Pessoauf.AsString:=VarToStr(ja.Field['endereco'].Field['uf'].Value);
Pessoacep.AsString:=VarToStr(ja.Field['endereco'].Field['cep'].Value);
pessoa.Post;
end;
end else
ShowMessage('não carregou a lista');
end;
except
on E : Exception do
begin
ShowMessage('Erro: '+e.message);
end;
end;
Mais Respostas
Dorivan Sousa
19/06/2015
Danilo Pereira
19/06/2015
Dorivan Sousa
19/06/2015
nesse codigo abaixo eu trato o result de um servidor json em delphi e alimento um clientdataset (vc pode colocar no objeto), por isso eu pego primeiro o filed 'result'... fiz esse ha algum tempo usando o servidor no delphi xe e o cliente no delphi 7.
var
lHTTP: TIdHTTP;
lStream: TStringStream;
Retorno: WideString;
aURL: String;
i: integer;
js: TlkJSONobject;
ja2, ja: TlkJSONlist;
param: String;
ip: String;
begin
try
if Valida_Lojas(Loja) then
ip:=DM_Cadastro.QryLojasIP_Fixo.AsString;
param:=IntToStr(Acao)+'/'+Procura+'/'+Data_Inicial+'/'+Data_Final+'/'+Loja;
aURL:='http://'+IP+':8090/datasnap/rest/TServerMethods1/GetRecebidasJson/'+param;
lHTTP := TIdHTTP.Create(nil);
//lHTTP.OnDisconnected:=DM_Json.IdHTTPJsonDisconnected;
//lHTTP.OnWorkBegin:=DM_Json.IdHTTPJsonWorkBegin;
//lHTTP.OnWorkEnd:=DM_Json.IdHTTPJsonWorkEnd;
lStream := TStringStream.Create(Retorno);
try
lHTTP.Request.Accept := 'text/javascript';
lHTTP.Request.ContentType := 'application/json';
lHTTP.Request.ContentEncoding := 'utf-8';
lHTTP.Request.BasicAuthentication:=True;
lHTTP.Request.Username:='user';
lHTTP.Request.Password:=sSenha_HTTP_Json;
lHTTP.Get(aUrl, lStream);
lStream.Position := 0;
Retorno := lStream.ReadString(lStream.Size);
finally
FreeAndNil(lHTTP);
FreeAndNil(lStream);
end;
if Length(Retorno)=0 then
begin
lHTTP.Free;
lStream.Free;
Result:=False;
end else
begin
js := TlkJSON.ParseText(Retorno) as TlkJSONobject;
ja2 := js.Field['result'] as TlkJSONlist;
ja := ja2.child[0] as TlkJSONlist;
if ja.Count <= 0 then
begin
lHTTP.Free;
lStream.Free;
Result:=False;
end else
begin
DM_Json.QryRecebidas.EmptyDataSet;
for i:=0 to ja.Count-1 do
begin
DM_Json.QryRecebidas.Append;
DM_Json.QryRecebidasPARCELA.AsString:=VarToStr(ja.Child[i].Field['parcela'].Value);
DM_Json.QryRecebidasFATURA.AsString:=VarToStr(ja.Child[i].Field['fatura'].Value);
DM_Json.QryRecebidasVAL_ATUAL.AsFloat:=StrToFloat(VarToStr(ja.Child[i].Field['val_atual'].Value));
DM_Json.QryRecebidasVal_Recbto.AsFloat:=StrToFloat(VarToStr(ja.Child[i].Field['val_recbto'].Value));
DM_Json.QryRecebidasVal_Parcela.AsFloat:=StrToFloat(VarToStr(ja.Child[i].Field['val_parcela'].Value));
DM_Json.QryRecebidasJuros_Recbto.AsFloat:=StrToFloat(VarToStr(ja.Child[i].Field['juros_recbto'].Value));
DM_Json.QryRecebidasDATA_EMISSAO.AsDateTime:=Data_Json(VarToStr(ja.Child[i].Field['data_emissao'].Value));
DM_Json.QryRecebidasDATA_VENCTO.AsDateTime:=Data_Json(VarToStr(ja.Child[i].Field['data_vencto'].Value));
DM_Json.QryRecebidasData_Recbto.AsDateTime:=Data_Json(VarToStr(ja.Child[i].Field['data_recbto'].Value));
DM_Json.QryRecebidasTPO_COBRANCA.AsString:=VarToStr(ja.Child[i].Field['tpo_cobranca'].Value);
DM_Json.QryRecebidasCLIENTE.AsString:=VarToStr(ja.Child[i].Field['cliente'].Value);
DM_Json.QryRecebidasNOM_CLIENTE.AsString:=VarToStr(ja.Child[i].Field['nom_cliente'].Value);
DM_Json.QryRecebidasSTATUS.AsString:=VarToStr(ja.Child[i].Field['status'].Value);
DM_Json.QryRecebidasTpo_Recbto.AsString:=VarToStr(ja.Child[i].Field['tpo_recbto'].Value);
DM_Json.QryRecebidasRecebida_na_Loja.AsString:=VarToStr(ja.Child[i].Field['recebida_na_loja'].Value);
DM_Json.QryRecebidas.Post;
end;
Result:=True;
lHTTP.Free;
lStream.Free;
end;
end;
except
on E : Exception do
begin
Result:=False;
Principal.TraduzException('Erro: '+e.message,nil);
end;
end;
Danilo Pereira
19/06/2015
O Json que estou recebendo esta nesse formato:
[{"fone":"","inscMunicipal":"","bairro":"","nascimento":"1899-12-30T00:00:00.000Z","uf":"MG","inscEstRg":"","apelidoFantasia":".","cep":"","cnpjCpf":".","id":0,"numero":"","status":"T","razaoSocial":"CONSUMIDOR#","cidade":"","endereco":"","codigo":"000000","fazenda":[]]
Eu acho que ele não reconhece esse formato, tem alguma forma de driblar este problema?
Dorivan Sousa
19/06/2015
[{"fone":"","inscMunicipal":"","bairro":"","nascimento":"1899-12-30T00:00:00.000Z","uf":"MG","inscEstRg":"","apelidoFantasia":".","cep":"","cnpjCpf":".","id":0,"numero":"","status":"T","razaoSocial":"CONSUMIDOR#","cidade":"","endereco":"","codigo":"000000","fazenda":[]]
apresentou um erro
Parse error on line 21: ... ] ] ---------------------^ Expecting '}', ','
nao é um json valido. ta falando um "}' antes do ultimo "]"
Danilo Pereira
19/06/2015
O Json é este:
[
{
"codigo": "000000",
"status": "ATIVO",
"razaoSocial": "CONSUMIDOR#",
"apelidoFantasia": ".",
"cpfCnpj": ".",
"inscEstRg": null,
"inscMunicipal": "13",
"fone": null,
"endereco": {
"nomeLogradouro": null,
"numero": "",
"bairro": null,
"cidade": null,
"uf": "MG",
"cep": null
},
"nascimento": null,
"cupons": [],
"fazendas": []
}
]
Dorivan Sousa
19/06/2015
Danilo Pereira
19/06/2015
procedure TformPrincipal.Button2Click(Sender: TObject); var js: TlkJSONobject; ja2, ja: TlkJSONlist; jsonString:String; begin dm.RESTCliente.BaseURL := 'http://localhost:8080/WebServiceIntegracao/wscoopa/cliente/all'; dm.RESTRequisicao.Method := TRESTRequestMethod.rmGET; dm.RESTRequisicao.Resource := ''; dm.RESTRequisicao.Execute; jsonString := dm.RESTResposta.JSONValue.ToString; js := TlkJSON.ParseText(jsonString) as TlkJSONobject; end;
O erro ocorre nessa linha: js := TlkJSON.ParseText(jsonString) as TlkJSONobject;
Danilo Pereira
19/06/2015
function THelper.JsonToObjeto(valorString: String;classe: TClass): TObject;
var unMarshal : TJSONUnMarshal;
valorJson: TJSONValue;
begin
unMarshal := TJSONUnMarshal.Create;
valorJson := TJSONObject.ParseJSONValue(valorString);
result := (unMarshal.CreateObject(classe,TJSONObject(valorJson)));
end;
Dorivan Sousa
19/06/2015
voce tem q levar em consideracao o que vc ta recebendo, voce recebe uma list entao temq tratar uma lista.. o codigo abaixo faz o tratamento correto do seu formato de json
var
Json: WideString;
e, i: integer;
jl: TlkJSONlist;
ja: TlkJSONobject;
begin
try
Json:=Edit1.Text;
if Length(Json) > 0 then
begin
jl := TlkJSON.ParseText(Json) as TlkJSONlist;
if assigned(jl) then
begin
ja := jl.child[0] as TlkJSONobject;
pessoa.EmptyDataSet;
pessoa.Append;
pessoacodigo.AsString:=VarToStr(ja.Field['codigo'].Value);
pessoastatus.AsString:=VarToStr(ja.Field['status'].Value);
pessoarazaoSocial.AsString:=VarToStr(ja.Field['razaoSocial'].Value);
pessoaapelidoFantasia.AsString:=VarToStr(ja.Field['apelidoFantasia'].Value);
pessoacnpjCpf.AsString:=VarToStr(ja.Field['cpfCnpj'].Value);
pessoainscEstRg.AsString:=VarToStr(ja.Field['inscEstRg'].Value);
pessoainscMunicipal.AsString:=VarToStr(ja.Field['inscMunicipal'].Value);
pessoafone.AsString:=VarToStr(ja.Field['fone'].Value);
Pessoaendereco.AsString:=VarToStr(ja.Field['endereco'].Field['nomeLogradouro'].Value);
Pessoanumero.AsString:=VarToStr(ja.Field['endereco'].Field['numero'].Value);
Pessoabairro.AsString:=VarToStr(ja.Field['endereco'].Field['bairro'].Value);
Pessoacidade.AsString:=VarToStr(ja.Field['endereco'].Field['cidade'].Value);
Pessoauf.AsString:=VarToStr(ja.Field['endereco'].Field['uf'].Value);
Pessoacep.AsString:=VarToStr(ja.Field['endereco'].Field['cep'].Value);
pessoa.Post;
end else
ShowMessage('não carregou a lista');
end;
except
on E : Exception do
begin
ShowMessage('Erro: '+e.message);
end;
end;
Dorivan Sousa
19/06/2015
tem q entender a extrutura do json que vc ta trabalhando
function THelper.JsonToObjeto(valorString: String;classe: TClass): TObject;
var unMarshal : TJSONUnMarshal;
valorJson: TJSONValue;
begin
valorString:=trim(valorString); //remove os esaços em branco no inicio e no fim se houver
valorString:=Copy(valorString,2,length(valorString)); //remove o primeiro colchete
valorString:=Copy(valorString,1,length(valorString)-1); //remove o ultimo colchete
unMarshal := TJSONUnMarshal.Create;
valorJson := TJSONObject.ParseJSONValue(valorString);
result := (unMarshal.CreateObject(classe,TJSONObject(valorJson)));
end;
Danilo Pereira
19/06/2015
Danilo Pereira
19/06/2015
procedure TformPrincipal.Button2Click(Sender: TObject);
var
jl: TlkJSONlist;
ja: TlkJSONobject;
jsonString:String;
lista: TList<TCliente>;
i: integer;
cliente: TCliente;
begin
lista := TList<TCliente>.Create;
ja := TlkJSONobject.Create;
jl := TlkJSONlist.Create;
dm.RESTCliente.BaseURL := 'http://localhost:8080/WebServiceIntegracao/wscoopa/cliente/all';
dm.RESTRequisicao.Method := TRESTRequestMethod.rmGET;
dm.RESTRequisicao.Resource := '';
dm.RESTRequisicao.Execute;
jsonString := dm.RESTResposta.JSONValue.ToString;
jl := TlkJSON.ParseText(jsonString) as TlkJSONlist;
if Assigned(jl) then
begin
for i := 0 to jl.Count-1 do
begin
ja := jl.Child[i] as TlkJSONobject;
cliente := TCliente.Create;
cliente.codigo := VarToStr(ja.Field['codigo'].Value);
cliente.razaoSocial := VarToStr(ja.Field['razaoSocial'].Value);
cliente.status := VarToStr(ja.Field['status'].Value);
cliente.apelidoFantasia := VarToStr(ja.Field['apelidoFantasia'].Value);
cliente.cnpjCpf := VarToStr(ja.Field['cpfCnpj'].Value);
cliente.inscEstRg :=VarToStr(ja.Field['inscEstRg'].Value);
cliente.inscMunicipal := VarToStr(ja.Field['inscMunicipal'].Value);
lista.Add(cliente);
end;
end;
end;Outra coisa q eu queria saber, se aquele método q eu tinha feito antes, tem alguma maneira de fazer ele com lista, porque ele fica sendo genérico. Muito obrigado pela ajuda.
Dorivan Sousa
19/06/2015
acho que a solucao é com generics. no seu codigo voce ta recebendo uma lista e ta tentando jogar essa liga em um só objeto, o que fazer é usar uma lista desse objeto
http://www.andreanolanusse.com/pt/utilizando-generics-para-transformacao-generica-de-objetos-em-datasnap-2010/
Danilo Pereira
19/06/2015
function THelper.JsonListObjeto(valor: String; classe: TClass): TList<TObject>;
var lista:Tlist<TObject>;
jo: TJSONObject;
obj: TObject;
jl: TJSONArray;
i:integer;
unMarshal: TJSONUnMarshal;
begin
lista := TList<TObject>.Create;
jo := TJSONObject.Create;
obj := TObject.Create;
jl := TJSONArray.Create;
unMarshal := TJSONUnMarshal.Create;
jl := TJSONObject.ParseJSONValue(valor) as TJsonArray;
for i := 0 to jl.Count -1 do
begin
jo := jl.Items[i] as TJSONObject;
obj := unMarshal.CreateObject(classe,jo);
lista.Add(obj);
end;
result := lista;
end;Depois basta chamar a função:
procedure TformPrincipal.Button10Click(Sender: TObject);
var helper: THelper;
jsonString: string;
lista:Tlist<TCliente>;
begin
helper := THelper.Create;
lista := TList<TCliente>.Create;
jsonString := memo1.Text;// RECEBE UM JSON
lista := TList<TCliente>(helper.JsonListObjeto(jsonString,TCliente)) ;
end;Muito obrigado pela ajuda, espero que este método possa te ajudar também.
Pro.sys.poa
19/06/2015
Estive acompanhando a troca de informações entre vcs e pergunto:
- Vcs utilizam ou sabem se existe uma forma de utilizar os componentes TRestCliente/TRestRequest/TRestResponse no Delphi XE3?
Pergunto, pois preciso recuperar um json de uma API de conexão que utiliza o protocolo HTTP seguindo o modelo RestFull. E esta conexão possui parâmetros o "header" HTTP.
Consegui realizar com estes componentes via XE8, mas a aplicação que precisa recuperar estes dados é em XE3.
Obrigado.
Danilo Pereira
19/06/2015
http://docwiki.embarcadero.com/RADStudio/XE8/en/REST_Client_Library
No primeiro parágrafo fala que a biblioteca esta disponível para todas as plataformas delphi que são suportadas,eu procurei se tinha alguma forma de instalar/baixar a biblioteca e não encontrei, eu creio que a versão XE3 não tenha suporte para a biblioteca.
Dorivan Sousa
19/06/2015
tem como vc postar a msg com o codigo que vc utilizou com generics?
Danilo Pereira
19/06/2015
function THelper.JsonListObjeto(valor: String; classe: TClass): TList<TObject>;
var lista:Tlist<TObject>;
jo: TJSONObject;
obj: TObject;
jl: TJSONArray;
i:integer;
unMarshal: TJSONUnMarshal;
begin
lista := TList<TObject>.Create;
jo := TJSONObject.Create;
obj := TObject.Create;
jl := TJSONArray.Create;
unMarshal := TJSONUnMarshal.Create;
jl := TJSONObject.ParseJSONValue(valor) as TJsonArray;
for i := 0 to jl.Count -1 do
begin
jo := jl.Items[i] as TJSONObject;
obj := unMarshal.CreateObject(classe,jo);
lista.Add(obj);
end;
result := lista;
end;pra chamar:
procedure TformPrincipal.Button10Click(Sender: TObject);
var helper: THelper;
jsonString: string;
lista:Tlist<TCliente>;
begin
helper := THelper.Create;
lista := TList<TCliente>.Create;
jsonString := memo1.Text;// RECEBE UM JSON
lista := TList<TCliente>(helper.JsonListObjeto(jsonString,TCliente)) ;
end;Danilo Pereira
19/06/2015
Acabei usando o a biblioteca do LkJson msm, só q estou tendo um problema na hora de deserializar campos que possuem acentuação, no lugar do acento esta vindo um "?", tem alguma maneira de resolver isso?
Meu método ta +- assim: o problema esta vindo em campos que possuem acentos como a descrição.
jl := TlkJSON.ParseText(jsonString) as TlkJSONlist;
if Assigned(jl) then
begin
for i := 0 to jl.Count-1 do
begin
ja := jl.Child[i] as TlkJSONobject;
produto := TProduto.Create;
produto.codigo := VarToStr(ja.Field['codigo'].Value);
produto.descricao := VarToStr(ja.Field['descricao'].Value);
produto.estMax := (ja.Field['estMax'].Value);
produto.precoVenda := ja.Field['precoVista'].Value;
produto.unidadeMedida := ja.Field['unidadeMedida'].Value;
produto.estMin := ja.Field['estMin'].Value;
end;
end;
Valter Kettner
19/06/2015
Estou começando a trabalhar com o JSON no Delphi e estou encontrando uma dificuldade.
Tenho que ler o retorno de uma API que nela irá retornar os pedidos, itens e complementos..
Os dados dos clientes, eu consigo capturar certinho pelo delphi, agora quando vou para os itens não estou conseguindo, o ID do item consigo e o nome do produto só consigo quando o produto não tem complemento, seria um subgrupo.Como faço para capturar os itens? Nao sei mais o que fazer.. se puderem me dar uma ajuda.
Abaixo envio o codigo fonte e a estrutura da APP
var
jl: TlkJSONlist;
ja,ja2: TlkJSONobject;
jsonString: string;
i: integer;
begin
ja := TlkJSONobject.Create;
jl := TlkJSONlist.Create;
jl := TlkJSON.ParseText(memo2.Text) as TlkJSONlist;
if Assigned(jl) then
begin
for i := 0 to jl.Count - 1 do
begin
ja := jl.Child[i] as TlkJSONobject;
ShowMessage(VarToStr(ja.Field['id'].Value)+' '+VarToStr(ja.Field['client'].Field['name'].Value));
ShowMessage(VarToStr(ja.Field['items'].Field['name'].Value));
end;
end;
200
Content-Type: application/json
[
{
"id": 1234567890,
"client": {
"name": "José da Silva",
"phone": "5599112233",
"email": "josesilva@gmail.com"
},
"time": "2015-7-27 13:27:0",
"discount": 0,
"change": 0,
"payment": "VISA-CREDIT",
"status": "WAITING",
"delivery": {
"delivery": "DELIVERY",
"address": "Av. Nossa Senhora das Dores",
"price": 6.5,
"time": 50,
"number": "768",
"complement": "ap 202 fundo",
"district": "Nossa Senhora das Dores",
"reference": ""
},
"statistics": {
"company": 2,
"delivery_much": 32
},
"company_id": 1234,
"total_price": 29,
"items": [
{
"id": 14719,
"name": "Pastel",
"description": "Pastel frito (Calabresa, mussarela, tomate, cebola, orégano, pimentão e azeitona)",
"comments": "",
"price_id": 16920,
"price": 22.5,
"groups": [
{
"id": 4671,
"flavor": true,
"additionals": [
{
"id": 39769,
"name": "Brócolis",
"description": "Brócolis com catupiry",
"price": 4.7
}
],
"name": "Sabor adicional (pastel misto)"
}
]
}
],
"cc_number": "498400"
}
]
Danilo Pereira
19/06/2015
Código:
jl := TlkJSON.ParseText(TEncoding.ASCII.GetString(TEncoding.ASCII.GetBytes(jsonString))) as TlkJSONlist;
if Assigned(jl) then
begin
for i := 0 to jl.Count-1 do
begin
ja := jl.Child[i] as TlkJSONobject;
cliente := TCliente.Create;
cliente.codigo := VarToStr(ja.Field['codigo'].Value);
cliente.razaoSocial := VarToStr(ja.Field['razaoSocial'].Value);
cliente.status := VarToStr(ja.Field['status'].Value);
cliente.apelidoFantasia := VarToStr(ja.Field['apelidoFantasia'].Value);
cliente.cpfCnpj := VarToStr(ja.Field['cpfCnpj'].Value);
cliente.inscEstRg := VarToStr(ja.Field['inscEstRg'].Value);
cliente.inscMunicipal := VarToStr(ja.Field['inscMunicipal'].Value);
cliente.endereco := VarToStr(ja.Field['nomeLogradouro'].Value);
cliente.numero := VarToStr(ja.field['numero'].Value);
cliente.bairro := VarToStr(ja.Field['bairro'].Value);
cliente.cidade := VarToStr(ja.Field['cidade'].Value);
cliente.uf := VarToStr(ja.Field['uf'].Value);
cliente.cep := VarToStr(ja.Field['cep'].Value);
cliente.nascimento := VarToDateTime(ja.Field['nascimento'].Value);
cliente.fone := VarToStr(ja.Field['contato'].Field['telPrincipal'].Value);
cliente.telefoneSecundario := VarToStr(ja.Field['contato'].Field['telSecundario'].Value);
cliente.telefoneCelular := VarToStr(ja.Field['contato'].Field['telCelular'].Value);
cliente.email := VarToStr(ja.Field['contato'].Field['email'].Value);
if assigned(ja.Field['matriculas']) then
begin
listaMatricula := Tlist<TClienteMatricula>.create;
for j := 0 to ja.Field['matriculas'].Count -1 do
begin
matricula := TClienteMatricula.Create;
matricula.figura := VarToStr(ja.Field['matriculas'].Child[j].Field['figura'].Value);
matricula.bp := VarToStr(ja.Field['matriculas'].Child[j].Field['BP'].Value);
matricula.codigoUnicoMatricula := ja.Field['matriculas'].Child[j].Field['codUnicoMat'].Value;
matricula.matricula := VarToStr(ja.Field['matriculas'].Child[j].Field['matricula'].Value);
listaMatricula.Add(matricula);
end;
cliente.matriculas := listaMatricula;
end;
lista.Add(cliente);
end;
end;
end;
end;
JSON:
[
{
"cpfCnpj": "00470252634",
"contato": {
"telSecundario": "",
"email": "",
"telPrincipal": "(34)38311444",
"telCelular": ""
},
"status": "ATIVO",
"uf": "MG",
"matriculas": [
{
"figura": "ZCOO",
"BP": "0100000010",
"codUnicoMat": 1,
"matricula": "000001"
},
{
"figura": "ZCLI",
"BP": "0100000010",
"codUnicoMat": 2,
"matricula": "000002"
}
],
"razaoSocial": "Walter Pereira Nunes",
"inscEstRg": "",
"numero": "",
"codigo": "0100000010",
"bairro": "Centro",
"cidade": "Patrocínio",
"cep": "38740-000",
"inscMunicipal": "",
"nascimento": "1934-07-05",
"apelidoFantasia": "",
"nomeLogradouro": "Rua Marechal Floriano 228"
}
]Valter Kettner
19/06/2015
jl: TlkJSONlist;
ja, ja2: TlkJSONobject;
jsonString: string;
i, ii: integer;
begin
ja := TlkJSONobject.Create;
jl := TlkJSONlist.Create;
jl := TlkJSON.ParseText(memo2.Text) as TlkJSONlist;
if Assigned(jl) then
begin
for i := 0 to jl.Count - 1 do
begin
ja := jl.Child[i] as TlkJSONobject;
ShowMessage(VarToStr(ja.Field['id'].Value) + ' ' + VarToStr(ja.Field['client'].Field['name'].Value));
for ii := 0 to ja.Field['items'].Count - 1 do
begin
ShowMessage(VarToStr(ja.Field['items'].child[ii].Field['name'].Value));
end;
end;
end;
end;
Danilo Pereira
19/06/2015
Valter Kettner
19/06/2015
Danilo Pereira
19/06/2015
danilo.desenvolvimento@zixinformatica.com
Valter Kettner
19/06/2015
Dorivan Sousa
19/06/2015
Danilo Pereira
19/06/2015
trocando essa linha:
jl := TlkJSON.ParseText(jsonString) as TlkJSONlist;
por esta:
jl := TlkJSON.ParseText(TEncoding.ASCII.GetString(TEncoding.ASCII.GetBytes(jsonString))) as TlkJSONlist;
Porém agora vem sem o acento, mas já é melhor do que deixar o ponto de interrogação.Valter acredito que isso vai te ajudar também.
Valter Kettner
19/06/2015
Araujo Junior.
19/06/2015
Project ClientNew.exe raised exception class EConversionError with message 'Internal: Invalid pair name {"$type":"Union.Models.TParametros","$id":1,"FID":1,"FDE_PAR":"QUANTIDADE DE CARACTERES DO GRUPO","FTIP_VAL":"F","FDE_VAL_PAR":"3"}: expected type or ref'.
A função ficou assim:
function JsonListObjeto(valor: String; classe: TClass): TList<TObject>;
var
lista: TList<TObject>;
jo: TJSONObject;
obj: TObject;
jl: TJSONArray;
i: integer;
unMarshal: TJSONUnMarshal;
begin
lista := TList<TObject>.Create;
jo := TJSONObject.Create;
obj := TObject.Create;
jl := TJSONArray.Create;
unMarshal := TJSONUnMarshal.Create;
jl := TJSONObject.ParseJSONValue(Valor) as TJSONArray;
for i := 0 to jl.Count - 1 do
begin
jo := jl.Items[i] as TJSONObject;
obj := unMarshal.Unmarshal(jo); //AQUI OCORRE O ERRO
lista.Add(obj);
end;
result := lista;
end;
Alguem faz ideia do que eu possa fazer? Testei o Json abaixo no site http://jsonlint.com/ e o mesmo é valido.
{
"result": [
[{
"$type": "Union.Models.TParametros",
"$id": 1,
"FId": 1,
"FDescricao": "QUANTIDADE DE CARACTERES DO GRUPO",
"FTipoValor": "F",
"FValor": "3"
}, {
"$type": "Union.Models.TParametros",
"$id": 2,
"FId": 2,
"FDescricao": "QUANTIDADE DE CARACTERES DO SUB GRUPO",
"FTipoValor": "F",
"FValor": "3"
}]
]
}
Saudações a todos
Vanderlan Brandão
19/06/2015
mesmo sabendo que o post é um pouco antigo.
Teria alguma forma de eu passar o index e ele me retornar o nome do Field.
Pois eu sei como é a estrutura do Json.
Porem tenho que montar um log de registro mas não queria fazer isso campo a campo. queria fazer um FOR para pegar o FIELD e o RESULT.
Desde ja agradeço