先將需要Deserialize的文件檔案建立類別Class
generate c# classes from json
線上的工具如
http://json2csharp.com/
讀取Json檔案
NuGet 下載Newtonsoft.Json套件
using (StreamReader r = new StreamReader(@"F:\Download\temp.json"))
{
string json = r.ReadToEnd();
RootObject items = JsonConvert.DeserializeObject<RootObject>(json);
}
解下來的item就可以使用
即時水位資料擷取範例:
網址:https://data.gov.tw/dataset/25768
Json格式資料網址:
https://data.wra.gov.tw/Service/OpenData.aspx?format=json&id=2D09DB8B-6A1B-485E-88B5-923A462F475C
資料內容:
{"RealtimeWaterLevel_OPENDATA":[
{"StationIdentifier":"1140H048","RecordTime":"2017-10-31T14:20:00","WaterLevel":"29.10"}
,{"StationIdentifier":"1140H049","RecordTime":"2017-10-31T14:00:00","WaterLevel":"22.24"}
,{"StationIdentifier":"1140H058","RecordTime":"2017-10-31T14:20:00","WaterLevel":"4.20"}
,{"StationIdentifier":"1140H066","RecordTime":"2017-10-31T14:20:00","WaterLevel":"2.11"}
]}
json2csharp 轉換為class
public class RealtimeWaterLevelOPENDATA { public string StationIdentifier { get; set; } public DateTime RecordTime { get; set; } public string WaterLevel { get; set; } } public class RootObject { public List<RealtimeWaterLevelOPENDATA> RealtimeWaterLevel_OPENDATA { get; set; } }即時水位擷取程式碼:
沒有留言:
張貼留言