delphi - 如何使用delphi从json中获取值
问题描述
我有这个 json,我想获取fname值。我怎么能用德尔福做到这一点
{
"root":[
{
"customers":[
{
"fname":"George Makris",
"Age":12
}
]
}
]
}
这是我现在正在做的事情,但我认为这不是正确的方式
procedure TForm1.Button1Click(Sender: TObject);
var s,json:string;
myObj:TJSONObject;
myarr:TJSONArray;
begin
json:='{"root":[{"customers":[ { "fname":"George Makris","Age":12}]}]}';
myObj := TJSONObject.ParseJSONValue(json) as TJSONObject;
myarr := myObj.GetValue('root') as TJSONArray;
myObj := myarr.Items[0] as TJSONObject;
myarr := myObj.GetValue('customers') as TJSONArray;
myObj := myarr.Items[0] as TJSONObject;
s := myObj.GetValue('fname').value;
showmessage(s);
end;
解决方案
您的示例很接近,但会泄漏内存,特别是 ParseJSONValue 的结果。
我更喜欢使用 TryGetValue 来验证内容是否存在。它还通过使用的参数推断类型。这是两者的无泄漏示例。
procedure TForm3.btnStartClick(Sender: TObject);
var
s, JSON: string;
jo: TJSONObject;
myarr: TJSONArray;
begin
JSON := '{"root":[{"customers":[ { "fname":"George Makris","Age":12}]}]}';
jo := TJSONObject.ParseJSONValue(JSON) as TJSONObject;
try
if jo.TryGetValue('root', myarr) and (myarr.Count > 0) then
if myarr.Items[0].TryGetValue('customers', myarr) and (myarr.Count > 0) then
if myarr.Items[0].TryGetValue('fname', s) then
showmessage(s);
finally
jo.Free;
end;
end;
推荐阅读
- api - 如何设置一个基本 URL 以及在哪里为 api 调用在颤振 dio 中声明它?
- docker - Citrix NetScaler CPX:配置内容切换
- ios - 如何将 Pan Gesture Recognizer 从一个视图转移到另一个视图?
- sql - 如何在 Ruby on Rails 5.2 中将复杂的 Postgres SQL 查询/子查询转换为活动记录?
- swift - 如何从firebase填充加载的记录?
- javascript - 如何使用媒体源扩展将音频添加到视频流
- react-native - 如何创建带有结束日期的本地通知
- javascript - Web App IoT Hub 仅一台特定设备的数据可视化
- machine-learning - 在 keras 中使用 model.predict 时出现列表“索引超出范围”
- docusignapi - MAX_MEMBERS_EXCEEDED 已超过帐户的最大成员数