首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何利用delphi从json中获取值

如何利用delphi从json中获取值
EN

Stack Overflow用户
提问于 2018-11-01 09:25:56
回答 1查看 6.7K关注 0票数 3

我有这个json,我想得到fname值。我怎么能用德尔菲做这件事?

代码语言:javascript
复制
{  
   "root":[  
      {  
         "customers":[  
            {  
               "fname":"George Makris",
               "Age":12
            }
         ]
      }
   ]
}

我现在正在做的事情是这样的,但我不认为这是一条必经之路

代码语言:javascript
复制
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;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-01 11:26:39

您的示例已接近,但会泄漏内存,特别是ParseJSONValue的结果。

我更喜欢使用TryGetValue来验证内容是否存在。它还根据所使用的参数推断类型。这里有一个两者都没有泄漏的例子。

代码语言:javascript
复制
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;
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53098385

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档