Delphi 10.3中使用JSON


有一個對JSON處理的單元,在你需要使用JSON的單元里面引入"System.json",隨后你就可以用Delphi自己的json處理類了。

 

注意:
  1,JSON類創建后,里面所有元素不用管釋放,JSON類自己管理,千萬不要畫蛇添足啊!!!!!!
 
const
  // 演示用的JSON
  jsonString = '{"name":"張三", "other":["中國","程序員"]}';
 
const
  // 演示用的JSON
  jsonString = '{"name":"張三", "other":["中國","程序員"]}';


implementation


{$R *.fmx}


uses
  System.json; // Dephi自帶的JSON單元


procedure TForm1.Button1Click(Sender: TObject);
var
  JSONObject: TJSONObject; // JSON類
  i: Integer; // 循環變量
  temp: string; // 臨時使用變量
  jsonArray: TJSONArray; // JSON數組變量
begin


  if Trim(Memo1.Text) = '' then
  begin
    ShowMessage('要解析數據不能為空!');
  end
  else
  begin
    JSONObject := nil;
    try
      { 從字符串生成JSON }
      JSONObject := TJSONObject.ParseJSONValue(Trim(Memo1.Text)) as TJSONObject;


      if JSONObject.Count > 0 then
      begin


        { 1,遍歷JSON數據 }
        Memo2.Lines.Add('遍歷JSON數據:' + #13#10);


        Memo2.Lines.Add('JSON數據數量:' + IntToStr(JSONObject.Count));


        for i := 0 to JSONObject.Count - 1 do
        begin


          if i = 0 then
          begin
            temp := JSONObject.Get(i).ToString + #13#10;;
          end
          else
          begin
            temp := temp + JSONObject.Get(i).ToString + #13#10;
          end;


        end;


        { output the JSON to console as String }
        Memo2.Lines.Add(temp);


        Memo2.Lines.Add('------------------------------');


        { 2,按元素解析JSON數據 }
        Memo2.Lines.Add('按元素解析JSON數據:' + #13#10);
        temp := 'name = ' + JSONObject.Values['name'].ToString + #13#10;
        Memo2.Lines.Add(temp);


        // json數組
        jsonArray := TJSONArray(JSONObject.GetValue('other'));;
        if jsonArray.Count > 0 then
        begin


          // 得到JSON數組字符串
          temp := 'other = ' + JSONObject.GetValue('other').ToString + #13#10;


          // 循環取得JSON數組中每個元素
          for i := 0 to jsonArray.Size - 1 do
          begin
            temp := temp + IntToStr(i + 1) + ' : ' + jsonArray.Items[i]
              .Value + #13#10;
          end;


        end;


        Memo2.Lines.Add(temp);


      end
      else
      begin
        temp := '沒有數據!';
        Memo2.Lines.Add(temp);
      end;


    finally
      JSONObject.Free;
    end;
  end;


end;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM