我試圖將簡單的json反序列化爲ObservableCollection。當我爲反序列化設置斷點時,似乎沒有任何事情發生。該方法永遠不會完成,並且不會引發錯誤。我能夠得到JSON並轉換爲字符串,而不是反序列化爲ObservableCollection。無法將json反序列化爲ObservableCollection並綁定到Xamarin.Forms中的xaml
我錯過了什麼嗎?我已經查看了我可以找到的反序列化對象的每個代碼示例,但似乎無法使其工作。
這是我的Xamarin.Forms頁面的代碼。
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; }
}
}
這是我的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>
任何幫助瞭解這將是驚人的。
你的json數組[]包含在一個對象{}中 - 所以你的json和你想要反序列化的東西不匹配。你需要修正一個或另一個,所以他們都匹配。 – Jason
謝謝賈森。我改變了結構,並且能夠反序列化和綁定,沒有任何問題。我花了好幾個星期試圖弄清楚,所以謝謝。 – PeterG