Reputation:
I have an RESTclient and sending a response to a server. The response is a JSON. I am able to display all information in the console, but in this JSON, there is an array. To display the json im using a foreach loop, but i dont get the array in it. The Array object is null.
public class Test1
{
public string Name{ get; set; }
}
public class Test2
{
public IList<Test> test{ get; set; }
}
var test = response.Content.ReadAsAsync<IEnumerable<Test1>>().Result;
foreach (var b in test)
{
Console.WriteLine("{0}", b.Name);
}
}
So I explain: The Test1 class is the information of the array. I get all informaiton from the JSON with test2. But i want just the array with the "name" in it. I think the foreach loop is alright and the problem is with the var "test".
I hope you understood and someone can help me :/
Thank you
Upvotes: 0
Views: 392
Reputation: 344
In case your JSON response is in the correct format then the response is most likely being processed in the for loop before it was actually received as you are reading it asynchronously.
You will need to await the response by adding the await keyword before your ReadAsAsync call and also add the async keyword to the method declaration.
public async void OutputResponse()
{
var test = await response.Content.ReadAsAsync<IEnumerable<Test1>>();
foreach (var b in test)
{
Console.WriteLine("{0}", b.Name);
}
}
Upvotes: 1