![](/img/trans.png)
[英]After update of ObservableCollection Xamarin.Forms ListView sends null events
[英]Parse JSON API from Dictionary to ObservableCollection for ListView in Xamarin.Forms
我正在嘗試解析錯誤的API端點。
這是從API返回的原始JSON
{"posts":{"29.11.2018":[{"title":"xxx","image_url":null,"message":"xxxx","time":"08:30 AM"}]}
這是我的RootObject
public class Notification
{
[JsonProperty("posts")]
public Dictionary<string, List<Post>> posts { get; set; }
}
public class Post
{
[JsonProperty("title")]
public string title { get; set; }
[JsonProperty("image_url")]
public Uri imageUrl { get; set; }
[JsonProperty("message")]
public string message { get; set; }
[JsonProperty("time")]
public string time { get; set; }
}
我的服務等級
var notification = JsonConvert.DeserializeObject<Dictionary<string, Notification>>(apiContent); //Deserialize the JSON data
var _schoolNotification = new ObservableCollection<Post>(notification.Keys);
NotificationListView.ItemsSource = _schoolNotification;
我編輯的XAML
<StackLayout>
<Label Style="{StaticResource ListViewTitle}" Text="{Binding title}" />
<Label Text="{Binding message}" TextColor="{DynamicResource ListViewDateColor}" />
</StackLayout>
我面臨的問題是,我無法將此字典解析為Xamarin.Forms要使用的ObservableColection。
任何幫助將不勝感激。
我認為預覽答案是正確的,但需要投射,因此請嘗試
//Deserialize the JSON data
var notification = JsonConvert.DeserializeObject<Notification>(apiContent);
List<Post> posts = new List<Post>();
if (notification?.posts != null){
foreach(var item in notification.posts.Values){
posts.AddRange(item);
}
}
var _schoolNotification = new ObservableCollection<Post>(posts);
我建議通過jsonutils.com運行JSON響應,並在反序列化步驟中將生成的類用作模型。 它通常是簡單的證明,並且在嘗試手動定義類時消除了潛在的人為錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.