0

I'm getting JSON data back from a PHP call using TIdHTTP. I'm expecting to use TJSONObject but can't work out how to use it for this purpose. And there are no examples in the XE3 help.

Sample JSON data

[{"fleet_id":"2","fleet":"EMB195"},{"fleet_id":"3","fleet":"EMB175"},{"fleet_id"‌:"1","fleet":"DHC84-400Q"}]

I'm sure this is simple, but how!

Thanks.

Sir Rufo
  • 18,395
  • 2
  • 39
  • 73
Martin Moore
  • 733
  • 2
  • 8
  • 21
  • This quite [`detailed article`](http://www.sdn.nl/SDN/Artikelen/tabid/58/view/View/ArticleID/3230/Reading-and-Writing-JSON-with-Delphi.aspx) might help you to start. – TLama Mar 08 '13 at 18:55
  • Cheers - useful article but still can't work out how to assign 'random' json data to TJSONObject – Martin Moore Mar 08 '13 at 19:08
  • Do you mean 'any' json data, i.e. any type? – Jan Doggen Mar 08 '13 at 19:36
  • I know what I'm expecting as I'm responsible for sending it from the PHP. So could be a single pair or an array etc. The test data is [{"fleet_id":"2","fleet":"EMB195"},{"fleet_id":"3","fleet":"EMB175"},{"fleet_id":"1","fleet":"DHC84-400Q"}] – Martin Moore Mar 08 '13 at 19:43
  • Can you clarify what you want to achieve with TJSONObject? – Uwe Raabe Mar 08 '13 at 20:13
  • Good point! I'm trying to replicate the following javascript – Martin Moore Mar 08 '13 at 20:20
  • $.getJSON(URL.php, function(data) { $.each(data, function(key, val){ alert(val.field1+val.field2); }); // each }// function – Martin Moore Mar 08 '13 at 20:23
  • and accept that there may be a better way than using TJSONOBject – Martin Moore Mar 08 '13 at 20:24
  • Something like [`this`](http://pastebin.com/8SbSTq34) ? I wrote this just in editor as I don't have Delphi in version higher than 2009 by hand. And, I guess there might be more efficient ways to do the same and more efficient ways to do exactly what you need. – TLama Mar 08 '13 at 20:34
  • That looks interesting TLama. I'm falling asleep now, but will try it tomorrow!! – Martin Moore Mar 08 '13 at 20:39

1 Answers1

3

Use TJsonObject.ParseJsonValue to convert the input string into a JSON value:

var
  val: TJsonValue;

s := '[{"fleet_id":"2","fleet":"EMB195"},{"fleet_id":"3","fleet":"EMB175"},{"fleet_id"‌:"1","fleet":"DHC84-400Q"}]';
val := TJsonObject.ParseJsonValue(s);

In this case, the JSON happens to represent an array, so you can type-cast it to that:

var
  arr: TJsonArray;

arr := val as TJsonArray;

You can access the elements of the array with Get, and type-cast the results to TJsonObject.

var
  i: Integer;
  elem: TJsonObject;

for i := 0 to Pred(arr.Size) do begin
  elem := arr.Get(i) as TJsonObject;
end;

To inspect the properties of the object, you can use the Get method, which returns a TJsonPair holding the name and value.

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467