procedure TForm1.FormCreate(Sender: TObject);
var
json: String;
J: TJSONData;
begin
// We hold our json data in a string.
// The variable "json" is a string type.
// We can also use TJSONStringType instead of string.
json:='{"user":'+
'{ "userid": 1900,'+
'"username": "jsmith",'+
'"password": "secret",'+
'"groups": [ "admins", "users", "maintainers"]'+
'}'+
'}';
// We send our JSON data to TJSONData. This is line 1 of our code.
J:=GetJSON(json);
// We show the username from the data
// FindPath returns TJSONData
// So we use .AsString to convert it to string. This is line 2.
Caption := J.FindPath('user.username').AsString;
end;
Die Abfragen funktionieren, nur bei groups bekomm ich einen Fehler das er den Pfad nicht findet.
Wie komme ich jetzt an die Daten in der eckigen Klammer?
Die Abfrage von groups funktioniert auch in dem Beispiel nicht .
procedure TForm1.FormCreate(Sender: TObject);
var
json: String;
J: TJSONData;
i: Integer;
begin
// We hold our json data in a string.
// The variable "json" is a string type.
// We can also use TJSONStringType instead of string.
json:='{"user":'+
'{ "userid": 1900,'+
'"username": "jsmith",'+
'"password": "secret",'+
'"groups": [ "admins", "users", "maintainers"]'+
'}'+
'}';
// We send our JSON data to TJSONData. This is line 1 of our code.
J:=GetJSON(json);
// We show the username from the data
// FindPath returns TJSONData
// So we use .AsString to convert it to string. This is line 2.
Caption := J.FindPath('user.username').AsString;
// Groups
for i := 0 to J.FindPath('user.groups').Count - 1 do // How many Items are in the Group
begin
ShowMessage(J.FindPath('user.groups['+ i.ToString + ']').AsString); // Iterate with i as a string value through items
end;
end;
Nachtrag:
Die Group einträge sind wie ein Array zu betrachten, siehe eckige Klammern.
...
'"groups": [ "admins", "users", "maintainers"]'
// i = 0 i = 1 i = 2
// Das sind hier die im deinem Beispiel möglich werte die "i" annehmen kann
...
Wenn du also nur "admins" haben willst musst du das so machen:
var
json: String;
J, user: TJSONData;
groups: TJSONArray;
i: Integer;
begin
// We hold our json data in a string.
// The variable "json" is a string type.
// We can also use TJSONStringType instead of string.
json:='{"user":'+
'{ "userid": 1900,'+
'"username": "jsmith",'+
'"password": "secret",'+
'"groups": [ "admins", "users", "maintainers"]'+
'}'+
'}';
// We send our JSON data to TJSONData. This is line 1 of our code.
J:=GetJSON(json);
user:=J.GetPath('user');
groups := user.GetPath('groups') as TJSONArray;
for i:=0 to groups.Count-1 do
ShowMessage(groups.Strings[i]);
end;