解析天氣預報JSON數據


解析天氣預報JSON數據

JSON字符串

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

1)MORMOT SDK解析JSON:

uses
SynCommons;

procedure TForm1.Button5Click(Sender: TObject);
var
doc: variant;
json: RawUTF8;
count, i: Integer;
begin
doc := _JsonFast(JSON2); // json還原為variant
Memo1.Clear;
Memo1.Lines.Add(doc.error); // 0
Memo1.Lines.Add(doc.status); // success
Memo1.Lines.Add(doc.date); // 2014-03-04
Memo1.Lines.Add(doc.results._(0).currentCity); // 成都
count := doc.results._(0).weather_data._count; // 取JSON數組 長度
for i := 0 to count - 1 do // 遍歷JSON數組
Memo1.Lines.Add(doc.results._(0).weather_data._(i).weather);
end;

2)DELPHI官方庫解析JSON:

 procedure TfjsonDemo.Button1Click(Sender: TObject);
var
  root, results: TJSONObject;
  LItem: TJSONValue;
  weather: TJSONArray;
  StrJson: string;
  result: string;
  i: Integer;
begin
  StrJson := Memo1.Text;
  root := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(StrJson), 0) as TJSONObject;
  results := (root.GetValue('results') as TJSONArray).Get(0) as TJSONObject;
  weather := results.GetValue('weather_data') as TJSONArray;

  for i := 0 to weather.size - 1 do //應該是4條記錄
  begin
    LItem := (weather.Get(i) as TJSONObject).GetValue('weather'); //得到weather的值
    result := result + '|'+ LItem.Value;
  end;
  Memo2.Text := result;
end;  


免責聲明!

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



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