Stu Ayton
Stu Ayton

Reputation: 489

Deserializing dynamic json object to listbox databinding

I have the following json:

{
  "COMPETITIONS": [
    {
      "name": "Name 1",
      "id": "76-7011",
      "ltable": "0"
    },
    {
      "name": "Name 2",
      "id": "116-7",
      "ltable": "0"
    },
    {
      "name": "Name 3",
      "id": "217-68",
      "ltable": "0"
    }
  ]
}

This is deserialized as dynamic using Json.net

 dynamic jsonResponse = JsonConvert.DeserializeObject(result);

I want to pass this data to a listbox such as

lb.ItemsSource = jsonResponse

<Page.Resources>
        <DataTemplate x:Key="DataTemplate1">
            <Grid>
                <TextBlock x:Name="textBox" TextWrapping="Wrap" Text="{Binding name}" d:LayoutOverrides="Width, Height" Foreground="Black"/>
            </Grid>
        </DataTemplate>
    </Page.Resources>

But it tells me:

Error: BindingExpression path error: 'name' property not found on 'Newtonsoft.Json.Linq.JObject, Newtonsoft.Json, Version=7.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'. BindingExpression: Path='name' DataItem='Newtonsoft.Json.Linq.JObject, Newtonsoft.Json, Version=7.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'; target element is 'Windows.UI.Xaml.Controls.TextBlock' (Name='textBox'); target property is 'Text' (type 'String')

Any advice please at parse this to the listbox without moving away from dynamic and using classes?

Upvotes: 0

Views: 898

Answers (1)

Aliasgar Rajpiplawala
Aliasgar Rajpiplawala

Reputation: 656

You can create class to deserialize your JSON.

public class COMPETITION
{
    public string name { get; set; }
    public string id { get; set; }
    public string ltable { get; set; }
}

public class RootObject
{
    public List<COMPETITION> COMPETITIONS { get; set; }
}

than you can deserialize using the below code

var jsonResponse = JsonConvert.DeserializeObject<COMPETITION>(result);

Upvotes: 1

Related Questions