Reputation: 4560
I have consume rest service from xamarin form.But my listview not shown that.It shown lots of empty rows only.
[
{
"prodName":"abc",
"qty":142.0,
"price":110.0
},
{
"prodName":"efg",
"qty":20.0,
"price":900.0
}
]
<ListView x:Name="ProductsListView">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding prodName}" TextColor="Black"></Label>
<Label Text="{Binding price}" TextColor="Black"></Label>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
private async void GetProducts()
{
HttpClient client = new HttpClient();
var response = await client.GetStringAsync("http://myUrl/Api/Values");
var products = response;
ProductsListView.ItemsSource = products;
}
Upvotes: 0
Views: 55
Reputation: 81493
The problem is you are getting back a json results, and trying to push it in to a listView ItemSource. Instead use json.net to convert your json to products first
Given
public class Product
{
public string prodName { get; set; }
public double qty { get; set; }
public double price { get; set; }
}
Example
private async void GetProducts()
{
HttpClient client = new HttpClient();
var response = await client.GetStringAsync("http://myUrl/Api/Values");
var products = JsonConvert.DeserializeObject<List<Product>>(response);
ProductsListView.ItemsSource = products;
}
Upvotes: 2
Reputation: 34013
This is not how that works. What you are doing now is downloading the JSON as a raw string value and put that in the ListView
.
You will have to deserialise the downloaded string into a .NET object.
Define a model like this:
public class ApiModel
{
[JsonProperty("prodName")]
public string prodName { get; set; }
[JsonProperty("qty")]
public long qty { get; set; }
[JsonProperty("price")]
public long price { get; set; }
}
And get your results like this:
private async void GetProducts()
{
HttpClient client = new HttpClient();
var response = await client.GetStringAsync("http://myUrl/Api/Values");
var products = JsonConvert.DeserializeObject<ApiModel[]>(response);
ProductsListView.ItemsSource = products;
}
Your result JSON string will now be converted to an array of ApiModel
and the ListView
can read properties from that.
If you haven't done so already, install JSON.NET and import the right usings (probabably using Newtonsoft.Json;
and/or using Newtonsoft.Json.Converters;
).
You might want to read up on this stuff, for more information look here: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/data-cloud/consuming/rest
Upvotes: 3