七、Delphi10.3讀取JSON數組


一、Delphi讀取JSON數組是非常方便的,首先我們網上找一段JSON數據

{
 "error": 0,
 "status": "success",
 "date": "2014-03-04",
 "results": [{
  "currentCity": "成都",
  "weather_data": [{
   "date": "周二(今天, 實時:12℃)",
   "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/duoyun.png",
   "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/duoyun.png",
   "weather": "多雲",
   "wind": "北風微風",
   "temperature": "15 ~ 6℃"
  }, {
   "date": "周三",
   "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/yin.png",
   "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/xiaoyu.png",
   "weather": "陰轉小雨",
   "wind": "北風微風",
   "temperature": "14 ~ 7℃"
  }, {
   "date": "周四",
   "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/xiaoyu.png",
   "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/xiaoyu.png",
   "weather": "小雨",
   "wind": "北風微風",
   "temperature": "12 ~ 7℃"
  }, {
   "date": "周五",
   "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/xiaoyu.png",
   "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/xiaoyu.png",
   "weather": "小雨",
   "wind": "南風微風",
   "temperature": "9 ~ 6℃"
  }]
 }]
}

 

二、我們用Delphi讀取,代碼如下:

uses
  REST.Json,
  System.Json,
  System.Types,
  System.Json.Types,
  System.Json.Writers,
  System.Json.Builders,
  System.Json.Serializers;

procedure TForm1.Button7Click(Sender: TObject);
var
  m_JSONObject: TJSONObject;
  m_Item1, m_Item2, m_Item3, m_Item4: TJSONValue;
  m_Weather: TJSONArray;
  m_Str: string;
  m_Result: string;
  I: Integer;
begin
  // 讀JSON文本
  m_Str := Trim(Memo1.text);
  // 防止亂碼
  m_JSONObject := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(m_Str), 0) as TJSONObject;
  // 讀取results的數據
  m_JSONObject := (m_JSONObject.GetValue('results') as TJSONArray).Get(0) as TJSONObject;
  // 讀取results中的weather_data的數組
  m_Weather := m_JSONObject.GetValue('weather_data') as TJSONArray;
  // 循環讀天氣數據
  for I := 0 to m_Weather.size - 1 do
  begin
    // 取天氣值
    m_Item1 := (m_Weather.Get(I) as TJSONObject).GetValue('date');
    m_Item2 := (m_Weather.Get(I) as TJSONObject).GetValue('weather');
    m_Item3 := (m_Weather.Get(I) as TJSONObject).GetValue('wind');
    m_Item4 := (m_Weather.Get(I) as TJSONObject).GetValue('temperature');
    // 輸出
    Memo2.Lines.Add(Format('【日期%s】,【天氣%s】,【風速%s】,【溫度%s】', [m_Item1.Value, m_Item2.Value, m_Item3.Value, m_Item4.Value]));
  end;
  m_JSONObject.Free;
end;

三、運行一下,結果如下:

 

不忘初心,如果您認為這篇文章有價值,認同作者的付出,可以微信二維碼打賞任意金額給作者(微信號:382477247)哦,謝謝。

 


免責聲明!

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



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