2016-02-17 74 views
1

我想從一個通用的Windows Phone應用程序一個JSON文件來分析,但我不能轉換任務字符串轉換任務<string>串

public MainPage() 
    { 
     this.InitializeComponent(); 

     HttpClient httpClient = new HttpClient(); 
     String responseLine; 
     JObject o; 
     try 
     { 
      string responseBodyAsText; 

      HttpResponseMessage response = httpClient.GetAsync("http://localhost/list.php").Result; 

      //response = await client.PostAsync(url, new FormUrlEncodedContent(values)); 
      response.EnsureSuccessStatusCode(); 
      responseBodyAsText = response.Content.ReadAsStringAsync().Result; 
      // responseLine = responseBodyAsText; 
       string Website = "http://localhost/list.php"; 
      Task<string> datatask = httpClient.GetStringAsync(new Uri(string.Format(Website, DateTime.UtcNow.Ticks))); 
      string data = await datatask; 
      o = JObject.Parse(data); 
      Debug.WriteLine("firstname:" + o["id"][0]); 
     } 
     catch (HttpRequestException hre) 
     { 
     } 

我有錯誤在這行

string data = await datatask; 

我該如何解決它?

+1

'string data = datatask.Result;'工作嗎? – Enigmativity

回答

2

您不能在構造函數中使用await。你需要爲此創建一個async方法。

通常我不推薦使用async void,但是當您從構造函數中調用它時,它有點合理。

public MainPage() 
{ 
    this.InitializeComponent(); 
    this.LoadContents(); 
} 

private async void LoadContents() 
{ 
    HttpClient httpClient = new HttpClient(); 
    String responseLine; 
    JObject o; 
    try 
    { 
     string responseBodyAsText; 

     HttpResponseMessage response = await httpClient.GetAsync("http://localhost/list.php"); 

     //response = await client.PostAsync(url, new FormUrlEncodedContent(values)); 
     response.EnsureSuccessStatusCode(); 
     responseBodyAsText = await response.Content.ReadAsStringAsync(); 
     // responseLine = responseBodyAsText; 
      string Website = "http://localhost/list.php"; 
     Task<string> datatask = httpClient.GetStringAsync(new Uri(string.Format(Website, DateTime.UtcNow.Ticks))); 
     string data = await datatask; 
     o = JObject.Parse(data); 
     Debug.WriteLine("firstname:" + o["id"][0]); 
    } 
    catch (HttpRequestException hre) 
    { 
     // You might want to actually handle the exception 
     // instead of silently swallowing it. 
    } 
} 
+0

我嘗試這段代碼,但得到這個錯誤 Newtonsoft.Json.Json.dll類型的異常發生在Newtonsoft.Json.dll中,但未在用戶代碼 –

+0

@AlaEddineHelmiHaouala中處理,請檢查調試器下的數據字符串。很可能你正在處理格式錯誤的JSON(或非JSON內容)。 –

+0

感謝您的回答,但是當我調用異步方法來顯示我的產品列表時,它並未顯示在模擬器中,但顯示在控制檯中。 她有什麼問題? –

相關問題