解析天气预报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;  

posted @ 2018-04-11 16:35  delphi中间件  阅读(1471)  评论(0编辑  收藏  举报