1. 程式人生 > 實用技巧 >delphi自帶的Json單元讀取Json用MJson .GetValue<string>(‘path’)

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

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

{
    "date": "2014-03-04",
    "error": 0,
    "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℃

  FreeAndNil(MJson );
 end;
end;