TdZ TdZ - 3 months ago 10
JSON Question

List of Rootobject from JSON String

I get the JSON as only a rootobject.

var parkinfo = new List<RootObjectUtrechtCity>();
RootObjectUtrechtCity utrechtCityInfo = await ParkUtrechtCityProxy.GetUtrechtCity();
parkStationsUtrechtCity.ItemsSource = parkinfo;


I want to put those guys in a list, and bind it to xaml. how to, code looks good, but binding is a problem.

the jason is: https://stallingsnet.nl/api/1/parkingcount/utrecht

Thanx in advance, i'll credit you in my app.

Proxy

public class ParkUtrechtCityProxy
{
public async static Task<RootObjectUtrechtCity> GetUtrechtCity()
{
var http = new HttpClient();
var response = await http.GetAsync("https://stallingsnet.nl/api/1/parkingcount/utrecht");
var result = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<RootObjectUtrechtCity>(result);
return data;
}
}

public class RootObjectUtrechtCity
{
public int totalPlaces { get; set; }
public string time { get; set; }
public int freePlaces { get; set; }
public string facilityName { get; set; }
public int occupiedPlaces { get; set; }
}


XAML

<ListView x:Name="parkStationsUtrechtCity"
Grid.Row="1">
<ListView.ItemTemplate>
<DataTemplate>
<RelativePanel>
<TextBlock Name="parkPlacesUtrecht"
Text="{Binding facilityName}"/>
<TextBlock Name="parkAvailableUtrecht"
Text="{Binding freePlaces}"
RelativePanel.Below="parkPlacesUtrecht"/>
</RelativePanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

Answer

Your JSON payload looks like this from C# POCO point of view:

public class RootObject
{
    public int totalPlaces { get; set; }
    public string time { get; set; }
    public int freePlaces { get; set; }
    public string facilityName { get; set; }
    public int occupiedPlaces { get; set; }
}

So if ParkUtrechtCityProxy.GetUtrechtCity() gets your json feed from the source and deserializes it properly, the code should looke like the following:

var parkinfo = new List<RootObjectUtrechtCity>();
parkinfo  = await ParkUtrechtCityProxy.GetUtrechtCity();
parkStationsUtrechtCity.ItemsSource = parkinfo;

Update

Update your proxy accordingly to make sure the JSON is serialized properly

    public async static Task<IEnumerable<RootObjectUtrechtCity>> GetUtrechtCity()
    {
        var http = new HttpClient();
        var response = await http.GetAsync("https://stallingsnet.nl/api/1/parkingcount/utrecht");
        var result = await response.Content.ReadAsStringAsync();
        var data = JsonConvert.DeserializeObject<List<RootObjectUtrechtCity>>(result);
        return data;
    }
Comments