I want to parse from a JSON file in a universal windows phone application but I can't convert task to 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)
{
}
I have error in this line
string data = await datatask;
how can I fix it?
Looking into this documentation, you can get that using: Result property.
For Example:
Task<int> task1 = myAsyncMethod(); //You can also use var instead of Task<int>
int i = task1.Result;
You cannot use await
inside a constructor. You'll need to create an async
method for that.
Generally I don't recommend using async void
, but when you're calling it from the constructor it's somewhat justified.
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.
}
}
Try this:
Task<string> post = postPostAsync("Url", data).Result.Content.ReadAsStringAsync();
post.Result.ToString();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With