2017-04-26 31 views
0

我試圖將簡單的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> 

任何幫助瞭解這將是驚人的。

+1

你的json數組[]包含在一個對象{}中 - 所以你的json和你想要反序列化的東西不匹配。你需要修正一個或另一個,所以他們都匹配。 – Jason

+0

謝謝賈森。我改變了結構,並且能夠反序列化和綁定,沒有任何問題。我花了好幾個星期試圖弄清楚,所以謝謝。 – PeterG

回答

0

alerts嵌套在根對象下,因此您無法直接反序列化它。

但是,你可以試試這個:

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

這會幫助你理解這個問題: enter image description here

,你擁有的JSON是像RootObjectWithNestedNumberList,但你嘗試反序列化它作爲SimpleNumberList。顯然,這不會起作用。

+0

我不太明白這是什麼意思,但我非常感興趣。你知道哪裏會有文檔嗎? – PeterG

+0

它更多的是通用的JSON理解。我可以給你[這裏](http://stackoverflow.com/documentation/json/topics),但它不會真的有幫助。 – Xiaoy312

+0

這與我推薦的基本相同 - 它將數據解析爲一個通用的json容器,只提取數組,然後將其反序列化 – Jason

相關問題