简体   繁体   中英

Unable to Deserialize json into an ObservableCollection and bind to xaml in Xamarin.Forms

I am trying to deserialize simple json to an ObservableCollection. When I set a breakpoint for the Deserialization nothing seems to happen. The method never completes and it doesn't throw an error. I am able to get the json and convert to a string, just not deserialize to an ObservableCollection.

Am I missing something? I have looked at every code example I could find for deserializing to an object and can't seem to make it work.

This is the code for my Xamarin.Forms page.

public partial class Notification : ContentPage
{
    public Notification()
    {
        InitializeComponent();
        this.BindingContext = NotificationData();
    }

    public async Task NotificationData()
    {
        ObservableCollection<Alert> notification = await GetAlert();
        NotificationList.ItemsSource = notification;
    }
    public static async Task<ObservableCollection<Alert>> GetAlert()
    {
        string WPPosts = "https://www.url.com/alerts.json";
        HttpClient client = new HttpClient();
        var response = await client.GetAsync(WPPosts).ConfigureAwait(false);

        if (response != null)
        {
            ObservableCollection<Alert> data = new ObservableCollection<Alert>();
            string content = response.Content.ReadAsStringAsync().Result;
            //string content_sanitized = RemoveHTMLTags(content);
            data = JsonConvert.DeserializeObject<ObservableCollection<Alert>>(content);
            return data;
        }
        else { return null; }
    }
    public class Alert
    {
        public string title { get; set; }
        public string imgUrl { get; set; }
        public string content { get; set; }
    }

    public class RootObject
    {
        public List<Alert> alerts { get; set; }
    }
}

This is my Xaml.

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" Title="News 
and Alerts" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
x:Class="JenksTrash.Notification" xmlns:local="clr-
namespace:JenksTrash" >
<ListView x:Name="NotificationList">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="1" />
                        <ColumnDefinition Width="7*" />
                    </Grid.ColumnDefinitions>
                        <Label Text="{Binding title}" FontAttributes="Bold" />
                        <Label Text="{Binding content}" FontAttributes="Bold" />
                    </Grid>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Any help understanding this would be amazing.

alerts are nested under a root object, hence why you can't deserialize it directly.

But, you can try this:

JObject.Parse(content)
    .SelectToken("alerts")
    .ToObject<ObservableCollection<Alert>>();

This should help you understand the problem: 在此处输入图片说明

The json that you have is like RootObjectWithNestedNumberList , but you were trying to deserialize it as a SimpleNumberList . Obviously, it wasn't going to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM