Geiger8 その3
 2013年5月27日
HPからのJsonデータの取得にちょっとハマった。
HttpWebRequestとWebResponseを使うらしい。
MSDNのサンプルをパクったけど、Taskのasyncとawaitでまたハマった。
async/awaitの場合、戻り値有のTaskでないと、ラムダの中で親の変数に値入れても反映されないようだ。ゥゥゥ・・・
Stremを取得した後は、System.Runtime.Serialization.Jsonで、オブジェクト化してくれた。
モデルはデータコントラクト使うんだな。
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50  | 
						using System.Runtime.Serialization.Json; using System.Runtime.Serialization; using System.Threading.Tasks; using System.Net; [DataContract] public class CPMInfo {     [DataMember(Name = "date")]     public string date { get; set; }     [DataMember(Name = "data")]     public int data { get; set; } } protected override void OnNavigatedTo(NavigationEventArgs e) {     var task = Task.Run<MemoryStream>(async () =>     {         // The downloaded resource ends up in the variable named content.         var content = new MemoryStream();         // Initialize an HttpWebRequest for the current URL.         var webReq = (HttpWebRequest)WebRequest.Create(@"http://xxxxx.net/jsonget.php");         // Send the request to the Internet resource and wait for         // the response.         using (WebResponse response = await webReq.GetResponseAsync())         {             // Get the data stream that is associated with the specified URL.             using (Stream responseStream = response.GetResponseStream())             {                 // Read the bytes in responseStream and copy them to content.                   responseStream.CopyTo(content);             }         }         // Return the result as a byte array.         return content;     });     task.Wait();     MemoryStream urlContents = task.Result;     if (urlContents == null)         return;     Debug.WriteLine(Encoding.UTF8.GetString(urlContents.ToArray(), 0, (int)urlContents.Length));     urlContents.Seek(0, SeekOrigin.Begin);     var s = new DataContractJsonSerializer(typeof(List<CPMInfo>));     var jo = s.ReadObject(urlContents) as List<CPMInfo>;  | 
					
一応、Listになったけど、全取得だからやっぱり遅いな。。。
