To use the System.JSON unit in Delphi, you will need to include it in the uses clause of your project.
Here is an example of how you can use the System.JSON unit to parse a JSON string and access its values:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
uses System.JSON; procedure Example; var JSONValue: TJSONValue; JSONObject: TJSONObject; JSONArray: TJSONArray; I: Integer; begin //Parse a JSON string JSONValue = TJSONObject.ParseJSONValue(‘{key value}’); try //Check if the value is an object if JSONValue is TJSONObject then begin JSONObject := JSONValue as TJSONObject; //Access the value of the key field Writeln(JSONObject.Values[‘key’].Value); end; finally JSONValue.Free; end; //Parse a JSON array JSONValue := TJSONObject.ParseJSONValue(‘[1, 2, 3, 4]’); try //Check if the value is an array if JSONValue is TJSONArray then begin JSONArray := JSONValue as TJSONArray; //Iterate through the array for I := 0 to JSONArray.Count – 1 do Writeln(JSONArray.Items[I].Value); end; finally JSONValue.Free; end; end; |
This example demonstrates how to parse a JSON string and access the values of a JSON object and array.
You can also use the TJSONObject and TJSONArray classes to create JSON objects and arrays and convert them to strings using the ToJSON method.
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
uses System.JSON; procedure Example; var JSONObject: TJSONObject; JSONArray: TJSONArray; I: Integer; begin //Create a JSON object JSONObject := TJSONObject.Create; try JSONObject.AddPair(‘key’, ‘value’); //Convert the object to a string Writeln(JSONObject.ToJSON); finally JSONObject.Free; end; //Create a JSON array JSONArray := TJSONArray.Create; try for I = 1 to 4 do JSONArray.Add(I); //Convert the array to a string Writeln(JSONArray.ToJSON); finally JSONArray.Free; end; end; |
Leave a Reply