grantful 3 Posted August 8, 2023 I am getting a json response from here http://www.thecocktaildb.com/api/json/v1/1/search.php?s=margarita The response has different drinks for margarita. I can pick the fist drink info just fine . I am trying to loop through the drinks and load then in an array and put the array into a listbox so i can choose which drink i want to look at. var MainJson, Result: TJSONObject; s: String; i: integer; relultListbox: TJSONArray; begin Form2.RESTClient1.BaseURL := 'https://www.thecocktaildb.com/api/json/v1/1/search.php?s=' + Edit7.Text; Form2.RESTRequest1.Execute; Memo4.Text := Form2.RESTResponse1.JSONText; Result := TJSONObject.ParseJSONValue(Form2.RESTResponse1.Content) as TJSONObject; relultListbox := TJSONObject.ParseJSONValue(Form2.RESTResponse1.Content) as TJSONArray; for I := 0 to relultListbox.Size - 1 do begin ListBox1.Items.Add(relultListbox.Items[I].Value); end; MainJson := Result.GetValue<TJSONObject>('drinks[0]'); Edit8.Text := MainJson.GetValue<string>('strDrink'); MainJson := Result.GetValue<TJSONObject>('drinks[1]'); Memo5.Text := MainJson.GetValue<string>('strInstructions'); relultListbox := TJSONObject.ParseJSONValue(Form2.RESTResponse1.Content) as TJSONArray; for I := 0 to relultListbox.Size - 1 do begin ListBox1.Items.Add(relultListbox.Items[I].Value); end; I am getting invalid class typecast. I am not sure if i need to load the json into an array. Thanks for any help with this. Share this post Link to post
aehimself 396 Posted August 8, 2023 (edited) You simply can iterate through the members of the array, like: Var jval: TJsonValue; jarr: TJsonArray; begin // jarr := myJson.GetValue(‘drinks’) As TJsonArray; for jval in jarr do // … end; p.s.: sorry, I can not find how to format as code from my phone 😞 Edited August 8, 2023 by aehimself Share this post Link to post
grantful 3 Posted August 8, 2023 Thanks for pointing me in the right direction. Here is working code for anyone who may need to do the same thing uses system.json; var MainJson, Result: TJSONObject; reslultListbox: TJSONArray; begin Form2.RESTClient1.BaseURL := 'https://www.thecocktaildb.com/api/json/v1/1/search.php?s=' + Edit7.Text; Form2.RESTRequest1.Execute; Memo4.Text := Form2.RESTResponse1.JSONText; Result := TJSONObject.ParseJSONValue(Form2.RESTResponse1.Content) as TJSONObject; reslultListbox := Result.GetValue('drinks') as TJSONArray; // reslultListbox:= TJSONObject.ParseJSONValue('drinks') as TJSONArray; for var JSONValue in reslultListbox do begin ListBox1.Items.Add((JSONValue as TJSONObject).GetValue('strDrink') .ToString); end; MainJson := Result.GetValue<TJSONObject>('drinks[0]'); Edit8.Text := MainJson.GetValue<string>('strDrink'); MainJson := Result.GetValue<TJSONObject>('drinks[0]'); Memo5.Text := MainJson.GetValue<string>('strInstructions'); Share this post Link to post