简体   繁体   中英

Decode json using uJson for delphi

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM