簡體   English   中英

如何使用delphi從json獲取值

[英]How to get a value from json with delphi

我有這個json,我想獲取fname值。 我該如何用Delphi做到這一點

{  
   "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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM