Good not being a pro in delphi
I want to read a file json
and extract fields.
Good not being a pro in delphi
I want to read a file json
and extract fields.
Here is an example of how you make the Delphi call to your url and pick up the json values
function TForm3.getTemp: TTemp;
var
lHTTP: TIdHTTP;
lParamList: TStringList;
LJSONObject : TJSONObject;
j:integer;
jSubPar: TJSONPair;
jsonStringData : String;
begin
// chamada a URL
lParamList := TStringList.Create;
lHTTP := TIdHTTP.Create(nil);
try
jsonStringData := lHTTP.Post('http://www.nif.pt/?json=1&q=509442013', lParamList);
finally
lHTTP.Free;
lParamList.Free;
end;
// obtendo valores
LJSONObject := nil;
try
LJSONObject := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(jsonStringData), 0) as TJSONObject;
for j := 0 to LJSONObject.Size - 1 do begin
jSubPar := LJSONObject.Get(j); //pega o par no índice j
if jSubPar.JsonString.Value = 'data' then begin
jsonStringData := jSubPar.toString;
end;
end;
LJSONObject := nil;
LJSONObject := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(jsonStringData.Replace('"data":','',[rfReplaceAll])), 0) as TJSONObject;
Result := TTemp.Create;
for j := 0 to LJSONObject.Size - 1 do begin
// NOME DO CAMPO
jSubPar.JsonString.Value
// VALOR
Result.location := jSubPar.JsonValue.Value
// {"result":"success"
if (trim(jSubPar.JsonString.Value) = 'result') then
jSubPar.JsonValue.Value // RETORNO success
end;
finally
LJSONObject.Free;
end;
end;
I also did another function to return the value of a specific field:
function TForm3.getCamposJsonString(json, value:String): String;
var
LJSONObject: TJSONObject;
jSubPar: TJSONPair;
i,j:integer;
begin
LJSONObject := nil;
try
LJSONObject := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(json),0) as TJSONObject;
for j := 0 to LJSONObject.Size - 1 do begin
jSubPar := LJSONObject.Get(j); //pega o par no índice j
if (trim(jSubPar.JsonString.Value) = value) then
Result := jSubPar.JsonValue.Value;
end;
finally
LJSONObject.Free;
end;
end;