主要內容:
- Linq to XML
- Newtonsoft.Json.Linq來解析JSON
- 博客園RSS(http://www.cnblogs.com/rss)的解析
- UWP調用自己實現的Web API
1.Linq to XML
Linq to XML不是一個新鮮的話題了,網上以及各種資料對這個介紹都比較多。今天就簡單了解下,不做深入的研究。。。在代碼中生成XML文檔,使用Linq to XML會比Windows.Data.Xml.Dom命名空間下的類簡單,使用起來也更加靈活。Linq to XML是對Linq表達式的擴展,我們也可以在處理XML時用上Linq語句。
先直接上一段代碼:
XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", null)); XElement root = new XElement("students", new XElement("student", new XAttribute("id", "201313138063"), new XAttribute("name", "czh"), new XAttribute("age", 18)), new XElement("student", new XAttribute("id", "201313138064"), new XAttribute("name", "dyq"), new XAttribute("age", 19)), new XElement("student", new XAttribute("id", "201313138065"), new XAttribute("name", "wxk"), new XAttribute("age", 22)), new XElement("student", new XAttribute("id", "201313138069"), new XAttribute("name", "cmf"), new XAttribute("age", 20))); xdoc.Add(root); textBlock.Text= xdoc.ToString();
首先我們創建了一個XDocument對象,代表整個XML文檔,在創建這個對象時,我們傳入了一個XDeclaration對象,這個對象聲明了xml的基本信息(<?xml version="1.0" encoding="utf-8"?>)。XElement對象則對應着一個個的XML標簽元素,XAttribute則對應這些元素里的屬性。這段代碼里面,root對應着<studens>標簽,然后創建root時,我們傳入了多個XElement對象,這些對象對應着<students>里面的<student>標簽,然后把root添加到xdoc中,這樣一個XML文檔就創建完成了。對比上面的代碼和下面生成的XML看一下咯。
<?xml version="1.0"?> <students> <student age="18" name="czh" id="201313138063"/> <student age="19" name="dyq" id="201313138064"/> <student age="22" name="wxk" id="201313138065"/> <student age="20" name="cmf" id="201313138069"/> </students>
接着,我們把上面的XML轉化為對象列表,用列表控件進行顯示:
XDocument xdoc = XDocument.Parse(textBlock.Text); XElement root= xdoc.Root; var students = from student in root.Elements("student") select new { SId=(string)student.Attribute("id"), SName= (string)student.Attribute("name"), SAge = (int)student.Attribute("age") }; listView.ItemsSource = students;
在這里我們用到了Linq中的select語句,將root(對應於students)中的所有student元素轉換成了匿名對象,這個匿名對象有SId、SName、SAge三個屬性,然后將這些匿名對象組成的students(類型為IEnumerable<T>)綁定到ListView控件上顯示:
2.Newtonsoft.Json.Linq來解析JSON
Newtonsoft.Json.Linq是一個比較火的第三方JSON解析庫,我們來簡單使用下。。。在建好的項目上右擊“引用”節點,選擇“管理Nuget包”,然后在搜索欄里面輸入“Newtonsoft”,選擇第一個,點安裝就是了。我們要解析JSON數據來源於中國和世界天氣全能版(http://apistore.baidu.com/apiworks/servicedetail/478.html)
這個第三方庫使用起來還是比較方便的,我們主要用到了JObject、JToken、JArray三個類,直接貼代碼。
前台xaml:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <Grid.RowDefinitions> <RowDefinition Height="50"></RowDefinition> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> </Grid.RowDefinitions> <StackPanel Orientation="Horizontal" HorizontalAlignment="Center"> <TextBox x:Name="tbCity" Margin="10,10,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="235"/> <Button x:Name="btnSearch" Content="Search" HorizontalAlignment="Center" Margin="20,10,0,0" VerticalAlignment="Top" Click="btnSearch_Click"/> </StackPanel> <Grid Visibility="Collapsed" HorizontalAlignment="Center" Grid.Row="1" x:Name="now_grid"> <Grid.RowDefinitions> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition></ColumnDefinition> <ColumnDefinition></ColumnDefinition> </Grid.ColumnDefinitions> <TextBlock Grid.Row="0" VerticalAlignment="Center" HorizontalAlignment="Center" Grid.Column="0" Text="當前天氣狀況"></TextBlock> <TextBlock Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center" Grid.Column="0" Text="當前溫度(C)"></TextBlock> <TextBlock Grid.Row="2" VerticalAlignment="Center" HorizontalAlignment="Center" Grid.Column="0" Text="相對濕度(%)"></TextBlock> <TextBlock Grid.Row="3" VerticalAlignment="Center" HorizontalAlignment="Center" Grid.Column="0" Text="能見度(km)"></TextBlock> <TextBlock Grid.Row="4" VerticalAlignment="Center" HorizontalAlignment="Center" Grid.Column="0" Text="空氣質量指數"></TextBlock> <TextBlock Grid.Row="5" VerticalAlignment="Center" HorizontalAlignment="Center" Grid.Column="0" Text="PM2.5(ug/m³)"></TextBlock> <TextBlock Grid.Row="6" VerticalAlignment="Center" HorizontalAlignment="Center" Grid.Column="0" Text="空氣質量類別"></TextBlock> <TextBlock Grid.Row="7" VerticalAlignment="Center" HorizontalAlignment="Center" Grid.Column="0" Text="風向"></TextBlock> <TextBlock Grid.Row="8" VerticalAlignment="Center" HorizontalAlignment="Center" Grid.Column="0" Text="風力"></TextBlock> <TextBlock Margin="12,0,0,0" Grid.Row="0" Grid.Column="1" Text="{Binding Txt}"></TextBlock> <TextBlock Margin="12,0,0,0" Grid.Row="1" Grid.Column="1" Text="{Binding Tmp}"></TextBlock> <TextBlock Margin="12,0,0,0" Grid.Row="2" Grid.Column="1" Text="{Binding Hum}"></TextBlock> <TextBlock Margin="12,0,0,0" Grid.Row="3" Grid.Column="1" Text="{Binding Vis}"></TextBlock> <TextBlock Margin="12,0,0,0" Grid.Row="4" Grid.Column="1" Text="{Binding Aqi}"></TextBlock> <TextBlock Margin="12,0,0,0" Grid.Row="5" Grid.Column="1" Text="{Binding Pm25}"></TextBlock> <TextBlock Margin="12,0,0,0" Grid.Row="6" Grid.Column="1" Text="{Binding Qlty}"></TextBlock> <TextBlock Margin="12,0,0,0" Grid.Row="7" Grid.Column="1" Text="{Binding Winddir}"></TextBlock> <TextBlock Margin="12,0,0,0" Grid.Row="8" Grid.Column="1" Text="{Binding Windsc}"></TextBlock> </Grid> <FlipView Visibility="Collapsed" x:Name="fv" Grid.Row="2"> <FlipView.ItemTemplate> <DataTemplate> <Grid> <Grid.RowDefinitions> <RowDefinition Height="2*"></RowDefinition> <RowDefinition Height="5*"></RowDefinition> <RowDefinition Height="2*"></RowDefinition> </Grid.RowDefinitions> <StackPanel Orientation="Vertical"> <TextBlock Text="{Binding Date}" HorizontalAlignment="Center"></TextBlock> <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center"> <TextBlock Margin="48,0,0,0" Text="日出時間:"></TextBlock> <TextBlock Margin="12,0,0,0" Text="{Binding Astrosr}"></TextBlock> <TextBlock Margin="24,0,0,0" Text="日出時間:"></TextBlock> <TextBlock Margin="12,0,0,0" Text="{Binding Astross}"></TextBlock> </StackPanel> </StackPanel> <Grid Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center"> <Grid.RowDefinitions> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition></ColumnDefinition> <ColumnDefinition></ColumnDefinition> </Grid.ColumnDefinitions> <TextBlock Grid.Row="0" VerticalAlignment="Center" HorizontalAlignment="Center" Grid.Column="0" Text="相對濕度(%)"></TextBlock> <TextBlock Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center" Grid.Column="0" Text="降水概率"></TextBlock> <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Hum}"></TextBlock> <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Pop}"></TextBlock> <StackPanel Orientation="Horizontal" Grid.Row="2" Grid.ColumnSpan="2"> <TextBlock Margin="36,4,0,0" Text="最高溫度(C):"></TextBlock> <TextBlock Margin="12,4,0,0" Text="{Binding Tmpmax}"></TextBlock> <TextBlock Margin="24,4,0,0" Text="最低溫度(C):"></TextBlock> <TextBlock Margin="12,4,0,0" Text="{Binding Tmpmin}"></TextBlock> </StackPanel> <StackPanel Orientation="Horizontal" Grid.Row="3" Grid.ColumnSpan="2"> <TextBlock Margin="24,4,0,0" Text="白天天氣狀況:"></TextBlock> <TextBlock Margin="12,4,0,0" Text="{Binding Txt_d}"></TextBlock> <TextBlock Margin="24,4,0,0" Text="夜晚天氣狀況:"></TextBlock> <TextBlock Margin="12,4,0,0" Text="{Binding Txt_n}"></TextBlock> </StackPanel> </Grid> <StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center"> <TextBlock Margin="48,0,0,0" Text="風向:"></TextBlock> <TextBlock Margin="12,0,0,0" Text="{Binding Winddir}"></TextBlock> <TextBlock Margin="24,0,0,0" Text="風力:"></TextBlock> <TextBlock Margin="12,0,0,0" Text="{Binding Windsc}"></TextBlock> </StackPanel> </Grid> </DataTemplate> </FlipView.ItemTemplate> </FlipView> <Grid x:Name="sugestion_grid" Visibility="Collapsed" Grid.Row="3" Margin="12"> <Grid.RowDefinitions> <RowDefinition Height="2*"></RowDefinition> <RowDefinition Height="2*"></RowDefinition> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition></ColumnDefinition> <ColumnDefinition></ColumnDefinition> </Grid.ColumnDefinitions> <Grid Margin="8" Grid.Row="0" Grid.Column="0"> <Grid.RowDefinitions> <RowDefinition Height="auto"></RowDefinition> <RowDefinition Height="auto"></RowDefinition> <RowDefinition Height="auto"></RowDefinition> </Grid.RowDefinitions> <TextBlock Text="舒適度指數:"></TextBlock> <TextBlock Grid.Row="1" Text="{Binding Comfbrf}"></TextBlock> <TextBlock Grid.Row="2" Text="{Binding Comftxt}" TextWrapping="Wrap"></TextBlock> </Grid> <Grid Margin="8" Grid.Row="0" Grid.Column="1"> <Grid.RowDefinitions> <RowDefinition Height="auto"></RowDefinition> <RowDefinition Height="auto"></RowDefinition> <RowDefinition Height="auto"></RowDefinition> </Grid.RowDefinitions> <TextBlock Text="穿衣指數:"></TextBlock> <TextBlock Grid.Row="1" Text="{Binding Drsgbrf}"></TextBlock> <TextBlock Grid.Row="2" Text="{Binding Drsgtxt}" TextWrapping="Wrap"></TextBlock> </Grid> <Grid Margin="8" Grid.Row="1" Grid.Column="0"> <Grid.RowDefinitions> <RowDefinition Height="auto"></RowDefinition> <RowDefinition Height="auto"></RowDefinition> <RowDefinition Height="auto"></RowDefinition> </Grid.RowDefinitions> <TextBlock Text="感冒指數:"></TextBlock> <TextBlock Grid.Row="1" Text="{Binding Flubrf}"></TextBlock> <TextBlock Grid.Row="2" Text="{Binding Flutxt}" TextWrapping="Wrap"></TextBlock> </Grid> <Grid Margin="8" Grid.Row="1" Grid.Column="1"> <Grid.RowDefinitions> <RowDefinition Height="auto"></RowDefinition> <RowDefinition Height="auto"></RowDefinition> <RowDefinition Height="auto"></RowDefinition> </Grid.RowDefinitions> <TextBlock Text="運動指數:"></TextBlock> <TextBlock Grid.Row="1" Text="{Binding Sportbrf}"></TextBlock> <TextBlock Grid.Row="2" Text="{Binding Sporttxt}" TextWrapping="Wrap"></TextBlock> </Grid> </Grid> </Grid>
后台代碼:
private async void btnSearch_Click(object sender, RoutedEventArgs e) { HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("apikey", "你的apikey"); string url = "http://apis.baidu.com/heweather/pro/weather?city=" + tbCity.Text; HttpResponseMessage response = await httpClient.GetAsync(new Uri(url)); response.EnsureSuccessStatusCode(); string result = await response.Content.ReadAsStringAsync(); DeserilizeJson(result); } private void DeserilizeJson(string result) { JObject jsonobj = JObject.Parse(result); JArray jsonarry = JArray.Parse(jsonobj["HeWeather data service 3.0"].ToString()); WeathernowData(jsonarry); DailyforecastData(jsonarry); SuggestionsData(jsonarry); } private void WeathernowData(JArray jsonarry) { Weathernow now = new Weathernow(); JToken weather = jsonarry[0]["now"]; now.Txt = weather["cond"]["txt"].ToString(); now.Tmp = weather["tmp"].ToString(); now.Aqi = jsonarry[0]["aqi"]["city"]["aqi"].ToString(); now.Pm25 = jsonarry[0]["aqi"]["city"]["pm25"].ToString(); now.Qlty = jsonarry[0]["aqi"]["city"]["qlty"].ToString(); now.Hum = weather["hum"].ToString(); now.Vis= weather["vis"].ToString(); now.Winddir= weather["wind"]["dir"].ToString(); now.Windsc= weather["wind"]["sc"].ToString(); if (now_grid.Visibility == Visibility.Collapsed) now_grid.Visibility = Visibility.Visible; now_grid.DataContext = now; } private void DailyforecastData(JArray jsonarry) { List<Dailyforecast> dailyList = new List<Dailyforecast>(); JArray daily_forecast =JArray.Parse( jsonarry[0]["daily_forecast"].ToString()); for (int i = 0; i < daily_forecast.Count; i++) { dailyList.Add(new Dailyforecast() { Date = daily_forecast[i]["date"].ToString() , Astrosr=daily_forecast[1]["astro"]["sr"].ToString(), Astross= daily_forecast[1]["astro"]["ss"].ToString(), Hum = daily_forecast[i]["hum"].ToString(), Pop= daily_forecast[i]["pop"].ToString(), Tmpmax = daily_forecast[i]["tmp"]["max"].ToString(), Tmpmin = daily_forecast[i]["tmp"]["min"].ToString(), Txt_d = daily_forecast[i]["cond"]["txt_d"].ToString(), Txt_n = daily_forecast[i]["cond"]["txt_n"].ToString(), Winddir = daily_forecast[i]["wind"]["dir"].ToString(), Windsc = daily_forecast[i]["wind"]["sc"].ToString() }); } if (fv.Visibility == Visibility.Collapsed) fv.Visibility = Visibility.Visible; fv.ItemsSource = dailyList; } private void SuggestionsData(JArray jsonarry) { Suggestions suggestions = new Suggestions(); JToken suggestion = jsonarry[0]["suggestion"]; suggestions.Comfbrf = suggestion["comf"]["brf"].ToString(); suggestions.Comftxt = suggestion["comf"]["txt"].ToString(); suggestions.Drsgbrf = suggestion["drsg"]["brf"].ToString(); suggestions.Drsgtxt = suggestion["drsg"]["txt"].ToString(); suggestions.Flubrf = suggestion["flu"]["brf"].ToString(); suggestions.Flutxt = suggestion["flu"]["txt"].ToString(); suggestions.Sportbrf = suggestion["sport"]["brf"].ToString(); suggestions.Sporttxt = suggestion["sport"]["txt"].ToString(); if (sugestion_grid.Visibility == Visibility.Collapsed) sugestion_grid.Visibility = Visibility.Visible; sugestion_grid.DataContext = suggestions; }
Weathernow.cs:

/* "txt": "晴" //天氣狀況描述 "tmp": "32", //溫度 "hum": "20%", //相對濕度(%) "vis": "10", //能見度(km) "aqi": "30", //空氣質量指數 "pm25": "7", //PM2.5 1小時平均值(ug/m³) "qlty": "優", //空氣質量類別 "winddir": "北風", //風向 "windsc": "3級", //風力 */ public class Weathernow { public string Txt { get; set; } public string Tmp { get; set; } public string Hum { get; set; } public string Vis { get; set; } public string Aqi { get; set; } public string Pm25 { get; set; } public string Qlty { get; set; } public string Winddir { get; set; } public string Windsc { get; set; } }
Suggestions.cs:

/* //舒適度指數 "comfbrf": "較不舒適", //簡介 "comftxt": "白天天氣多雲,同時會感到有些熱,不很舒適。" //詳細描述 //穿衣指數 "drsgbrf": "炎熱", "drsgtxt": "天氣炎熱,建議着短衫、短裙、短褲、薄型T恤衫等清涼夏季服裝。" //感冒指數 "flubrf": "少發", "flutxt": "各項氣象條件適宜,發生感冒機率較低。但請避免長期處於空調房間中,以防感冒。" //運動指數 "sportbrf": "較適宜", "sporttxt": "天氣較好,戶外運動請注意防曬。推薦您進行室內運動。" //紫外線指數 "uvbrf": "中等", "uvtxt": "屬中等強度紫外線輻射天氣,外出時建議塗擦SPF高於15、PA+的防曬護膚品,戴帽子、太陽鏡。" */ public class Suggestions { public string Comfbrf { get; set; } public string Comftxt { get; set; } public string Drsgbrf { get; set; } public string Drsgtxt { get; set; } public string Flubrf { get; set; } public string Flutxt { get; set; } public string Sportbrf { get; set; } public string Sporttxt { get; set; } }
Dailyforecast.cs:

/* "date": "2015-07-02", //預報日期 "astrosr": "04:50", //日出時間 "astross": "19:47" //日落時間 "txt_d": "晴", //白天天氣狀況描述 "txt_n": "晴" //夜間天氣狀況描述 "hum": "14", //相對濕度(%) "pop": "0", //降水概率 "tmpmax": "34", //最高溫度 "tmpmin": "18" //最低溫度 "winddir": "東南風", //風向 "windsc": "3-4", //風力 */ public class Dailyforecast { public string Date { get; set; } public string Astrosr { get; set; } public string Astross { get; set;} public string Txt_d { get; set; } public string Txt_n { get; set; } public string Hum { get; set; } public string Pop { get; set; } public string Tmpmax { get; set; } public string Tmpmin { get; set; } public string Winddir { get; set; } public string Windsc { get; set; } }
我們來看截取的這一段JSON數據:
JObject jsonobj = JObject.Parse(result);
JArray jsonarry = JArray.Parse(jsonobj["HeWeather data service 3.0"].ToString());
JToken suggestion = jsonarry[0]["suggestion"];
suggestions.Comfbrf = suggestion["comf"]["brf"].ToString();
借助上面幾行代碼就可以取到第三行的“較舒適”三個字了,像jsonarry[0]["suggestion"]["comf"]["brf"]這樣來取相應的數據還是相當方便的,動手試試,不太難的。我這里之所以這么多代碼,是為了要解析出很多的JSON數據。。。。來看運行結果:(廢話:查詢結果依次是當前天氣,FilpView控件展示的未來十天天氣,一些天氣指數)
3.博客園RSS(http://www.cnblogs.com/rss)的解析
在UWP里面,Windows.Web.Syndication命名空間對訪問RSS源提供了比較好的支持,然而這次對博客園RSS的解析並沒有采用這個命名空間下的類,而是直接解析XML文檔來的。個人感覺在解析的時候還是遇到了一些坑的,里面貌似留了一些空格等東西,反正SelectNodes等的那個Xpath怎么寫都不太對,最后直接用GetElementsByTagName了,此痛試過就知道。。。我們的HttpClient類采用的是Windows.Web.Http命名空間下的,XmlDocument則來自Windows.Data.Xml.Dom命名空間。還是像以前提到的,XML解析用好”快速監視“根據情況動態調整一下,不太難的。ok,直接貼代碼,不做過多解釋。
前台xaml:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"></ColumnDefinition> <ColumnDefinition Width="*"></ColumnDefinition> </Grid.ColumnDefinitions> <ListView x:Name="listview" ItemClick="listview_ItemClick" IsItemClickEnabled="True"> <ListView.ItemTemplate> <DataTemplate> <StackPanel Orientation="Vertical" Margin="10"> <TextBlock TextWrapping="Wrap" Text="{Binding Title}" FontSize="18"/> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding AuthorName}" FontSize="15"/> <TextBlock Text="{Binding PublishedTime}" FontSize="15" Margin="30,0,10,0"/> </StackPanel> </StackPanel> </DataTemplate> </ListView.ItemTemplate> </ListView> <WebView x:Name="wv" Grid.Column="1"/> </Grid>
后台代碼:(廢話:把InitData方法放在MainPage的構造函數里面調用)
private async void InitData() { HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible;MSIE 10.0;Windows NT 6.2;WOW64;Trident/6.0)"); HttpResponseMessage response = await httpClient.GetAsync(new Uri("http://www.cnblogs.com/rss")); response.EnsureSuccessStatusCode(); string result = await response.Content.ReadAsStringAsync(); List<Article> articlelist = new List<Article>(); XmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(result); IXmlNode xn = xdoc.ChildNodes.Item(1); // feed XmlElement topxe = (XmlElement)xn; XmlNodeList nodelist = topxe.GetElementsByTagName("entry"); foreach (IXmlNode node in nodelist) { XmlNodeList xeIdnodelist = ((XmlElement)node).GetElementsByTagName("id"); XmlNodeList xeTitlenodelist = ((XmlElement)node).GetElementsByTagName("title"); XmlNodeList xePublishednodelist = ((XmlElement)node).GetElementsByTagName("published"); XmlNodeList xecontentnodelist = ((XmlElement)node).GetElementsByTagName("content"); XmlNodeList xeAuthornodelist = ((XmlElement)node).GetElementsByTagName("author"); string id = xeIdnodelist.Item(0).InnerText; string title = xeTitlenodelist.Item(0).InnerText.Split('-')[0]; string published = xePublishednodelist.Item(0).InnerText; string content = xecontentnodelist.Item(0).InnerText; string authorname = xeAuthornodelist.Item(0).ChildNodes.Item(1).InnerText; articlelist.Add(new Article() { Id = id, Title = title, AuthorName = authorname, PublishedTime = published, Content = content }); } listview.ItemsSource = articlelist; } private void listview_ItemClick(object sender, ItemClickEventArgs e) { Article article = e.ClickedItem as Article; wv.NavigateToString(article.Content); }
Article類:

public class Article { public string Id { get; set; } public string Title { get; set; } public string AuthorName { get; set; } public string PublishedTime { get; set; } public string Content { get; set; } }
運行結果:(廢話:我們用ListView控件來顯示文章的標題等信息,文章的內容由WebView控件來展示)
4.UWP調用自己實現的Web API
我們來利用ASP.NET Web API實現一個簡單的API接口供UWP客戶端來調用。由於本人的ASP.NET技術有限,所以這個API幾乎是靠Visual Studio來自動生成,我們的數據采用Database First的方式來實現。
Firstly,新建一個ASP.NET Web應用程序,然后來到下圖,為簡單起見,選擇“Empty”模板,然后選中“Web API”,點擊“確定”,ok。
Secondly,右擊項目的“Models”文件夾,依次,“添加”-->"新建項",在右邊選擇“數據”,然后選擇“ADO.NET 實體數據模型”,名稱處命名,點擊“添加”,ok
然后我們來到下圖,選擇“來自數據庫的Code First”,點擊“下一步”
接着是下圖
點擊新建連接,出現下圖,服務器名“.”表示本機,然后登陸到服務器,選擇要連接的數據庫,測試連接,連接成功,點擊“確定“即可
然后是此圖,我們這次只用到Books表,所有就只選中它了。點擊“完成”之后,會在Models文件夾下面生成許多的文件,自行查看。。。
前面這些步驟說起來比較麻煩,也可能還沒說清楚,由於我之前已經完成了編碼,再記錄的博客,也會漏掉一些內容,這些如果是自己操作熟了,會很簡單的。數據還可以采用Code First等方式,,,,,不詳述了。
Then,右擊“Controllers文件夾”,點擊添加控制器,如下圖,點擊“添加”
之后是這個,選擇數據上下文類和模型類,然后再點擊“添加”
點擊添加,然后會在Controller文件夾下生成BooksController.cs類文件(圖上的Books1Controller是因為我之前已完成編碼,已經有了BooksController。。。。),我們打開BooksController類,會看到自動生成了很多的方法(模板的強大力量啊,用起來確實很方便,由於只是演示,就用模板了。。。),代碼很多,這里就不貼了,里面的方法大多都對應一種HTTP請求的。
比如下面這個方法:
// GET: api/Books
public IQueryable<Books> GetBooks()
{
return db.Books;
}
我們生成並開始調試,然后瀏覽器會報錯:HTTP Error 403.14 - Forbidden,這時候,我們只需要在那個地址后面加上api/Books就ok,根據不同的瀏覽器會返回json或xml數據,其他的方法則類似。至此API接口已全部完成。
最后就是客戶端的調用了。分別采用了請求XML和JSON的方式,由於HTTP請求以及XML和JSON的解析,前面已經學習過,這里不再贅述,直接貼代碼。
請求XML數據:
private async void InitDataXml() { HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/xml")); HttpResponseMessage response = await httpClient.GetAsync(new Uri("http://localhost:64339/api/books")); response.EnsureSuccessStatusCode(); string result = await response.Content.ReadAsStringAsync(); List<Books> bookslist = new List<Books>(); XmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(result); IXmlNode xn = xdoc.ChildNodes.Item(0); XmlElement topxe = (XmlElement)xn; XmlNodeList nodelist = xn.ChildNodes; foreach (IXmlNode node in nodelist) { XmlElement xe = (XmlElement)node; XmlNodeList xenodelist = xe.ChildNodes; bookslist.Add(new Books() { book_Name =xenodelist.Item(3).InnerText, book_Author = xenodelist.Item(0).InnerText, book_Isbn = xenodelist.Item(2).InnerText, book_cate =xenodelist.Item(7).InnerText, book_Press = xenodelist.Item(4).InnerText, book_Rressdate = xenodelist.Item(6).InnerText, book_Remain = Convert.ToInt32(xenodelist.Item(5).InnerText) }); } listView.ItemsSource = bookslist; }
請求JSON數據:
private async void InitDataJson() { HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = await httpClient.GetAsync(new Uri("http://localhost:64339/api/books")); response.EnsureSuccessStatusCode(); string result = await response.Content.ReadAsStringAsync(); List<Books> bookslist = new List<Books>(); JsonArray arrays = JsonArray.Parse(result); for (int i = 0; i < arrays.Count; i++) { JsonObject obj = arrays.GetObjectAt((uint)i); bookslist.Add(new Books() { book_Name =obj.GetNamedString("book_Name"), book_Author = obj.GetNamedString("book_Author"), book_Isbn = obj.GetNamedString("book_Isbn"), book_cate =obj.GetNamedString("book_cate"), book_Press = obj.GetNamedString("book_Press"), book_Rressdate = obj.GetNamedString("book_Rressdate"), book_Remain = Convert.ToInt32(obj.GetNamedNumber("book_Remain")) }); } listView.ItemsSource = bookslist; }
Book.cs:

public class Books { public int book_Id { get; set; } public string book_Name { get; set; } public string book_Author { get; set; } public string book_Isbn { get; set; } public string book_cate { get; set; } public string book_Press { get; set; } public string book_Rressdate { get; set; } public int book_Remain { get; set; } }
運行結果:
借助於ASP.NET Web API,我們最終將SQL Server數據庫中的數據通過UWP應用進行了展示。(我發現最后的這個圖表示的意思有點不夠,懶得換了,懶)
好了,這就是本次的全部內容了,貌似有點亂,要Demo的留郵箱。太晚了,睡覺了,晚安!