delphi自帶的Json單元讀取Json用MJson .GetValue<string>(‘path’)

delphi自帶的Json單元讀取Json還是特別方便的。如下:

{
    "date": "2014-03-14",
    "error": 88,
    "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",
                    "temperature": "15 ~ 6℃",
                    "weather": "多雲",
                    "wind": "北風微風"
                },
                {
                    "date": "週三",
                    "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/yin.png",
                    "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/xiaoyu.png",
                    "temperature": "14 ~ 7℃",
                    "weather": "陰轉小雨",
                    "wind": "北風微風"
                },
                {
                    "date": "週四",
                    "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/xiaoyu.png",
                    "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/xiaoyu.png",
                    "temperature": "12 ~ 7℃",
                    "weather": "小雨",
                    "wind": "北風微風"
                },
                {
                    "date": "週五",
                    "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/xiaoyu.png",
                    "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/xiaoyu.png",
                    "temperature": "9 ~ 6℃",
                    "weather": "小雨",
                    "wind": "南風微風"
                }
            ]
        }
    ],
    "status": "success"
}

Delphi 程序如下:

uses
System.JSON



var
  MJsonTxt:string;
  MJson:TJSONObject ;
  Value,Value2:string;
begin
 MJsonTxt :=Memo1.Lines .Text ;
 MJson :=TJSONObject .ParseJSONValue(MJsonTxt )as TJSONObject ;
 if Assigned(MJson ) then
 begin
   Value :=MJson .GetValue<string>('results[0].weather_data[1].temperature');
   ShowMessage(Value ); //14 ~ 7℃

   Value := MJson.GetValue<string>('results[0].weather_data[2].weather');
    ShowMessage(Value ); // 小雨

    Value := MJson.GetValue<string>('date'); 
    ShowMessage(Value ); // 2014-03-14                   

    Value := MJson.GetValue<string>('error');  // 整數可以按字符串取出
    ShowMessage(Value ); // 88

    Value := inttostr(MJson.GetValue<Integer>('error')); // 也可按整數取出
    ShowMessage(Value ); // 88

  FreeAndNil(MJson );
 end;
end;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章