首页 > 解决方案 > 如何使用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;

标签: delphi

解决方案


您的示例很接近,但会泄漏内存,特别是 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;

推荐阅读