delphi json
时间: 2023-08-22 21:11:01 浏览: 63
在 Delphi 中,您可以使用 TJSONObject 和 TJSONArray 类来处理 JSON 数据。这两个类是 Delphi 提供的用于操作和构建 JSON 数据的核心类。以下是一些示例代码,演示了如何在 Delphi 中使用 TJSONObject 和 TJSONArray:
```delphi
var
JSONObject: TJSONObject;
JSONArray: TJSONArray;
JSONValue: TJSONValue;
begin
// 创建一个空的 JSON 对象
JSONObject := TJSONObject.Create;
// 添加属性和值到 JSON 对象
JSONObject.AddPair('name', 'John');
JSONObject.AddPair('age', TJSONNumber.Create(30));
JSONObject.AddPair('isMarried', TJSONBool.Create(True));
// 获取属性的值
ShowMessage(JSONObject.GetValue('name').Value);
ShowMessage(IntToStr((JSONObject.GetValue('age') as TJSONNumber).AsInt));
ShowMessage(BoolToStr((JSONObject.GetValue('isMarried') as TJSONBool).AsBoolean, True));
// 创建一个 JSON 数组
JSONArray := TJSONArray.Create;
// 向数组中添加元素
JSONArray.Add('Apple');
JSONArray.Add('Banana');
JSONArray.Add('Orange');
// 将数组添加到 JSON 对象中
JSONObject.AddPair('fruits', JSONArray);
// 获取数组中的元素
JSONValue := JSONArray.Items[0];
ShowMessage(JSONValue.Value);
// 清空 JSON 对象和 JSON 数组
JSONObject.Clear;
JSONArray.Clear;
JSONObject.Free;
JSONArray.Free;
end;
```
在上面的示例中,我们首先创建了一个空的 TJSONObject 对象,并使用 AddPair 方法将属性和对应的值添加到 JSON 对象中。我们使用字符串、TJSONNumber 和 TJSONBool 来分别表示属性的值。
要访问 JSON 对象的属性和值,我们可以使用 GetValue 方法获取属性对应的 TJSONValue,并使用 as 运算符将其转换为相应的类型。然后,我们可以使用 Value 或其他属性获取 JSON 值的实际值。
此外,在示例中,我们还创建了一个 TJSONArray 对象,并使用 Add 方法向数组中添加了三个字符串元素。然后,我们将该 JSON 数组作为属性添加到 JSON 对象中。
请注意,在使用完 JSONObject 和 JSONArray 对象后,记得释放它们的内存。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)