I have a JSON file that looks like this and I'm trying to decode it, but with no luck:
[
{
"FirstName": "Kim",
"Surname": "Jensen"
},
{
"FirstName": "Amery",
"Surname": "Mcmillan"
},
{
"FirstName": "Denton",
"Surname": "Burnett"
}
...
]
Using uJson with Delphi 2007, I know how to extract the data when the array has a name like this:
{
"Names": [
{
"FirstName": "Kim",
"Surname": "Jensen"
},
{
"FirstName": "Amery",
"Surname": "Mcmillan"
},
{
"FirstName": "Denton",
"Surname": "Burnett"
}
...
]
}
var
json: TJSONObject;
Text: String;
i: Integer;
begin
json := TJSONObject.create(jsontext);
for i:=0 to json.getJSONArray('Names').Length -1 do
begin
Text := json.getJSONArray('Names').getJSONObject(i).optString('FirstName');
...
end;
end;
But, this array has no name, and I have tried almost everything I can think of and still this simple thing has taking me hours to figure out.
In the JSON you are having trouble with, the top-level data is the array, so you need to parse it using TJSONArray
instead of TJSONObject
.
var
json: TJSONArray;
Text: String;
i: Integer;
begin
json := TJSONArray.create(jsontext);
try
for i := 0 to json.Length-1 do
begin
Text := json.getJSONObject(i).optString('FirstName');
...
end;
finally
json.Free;
end;
end;