繁体   English   中英

将字典中的JSON API解析为Xamarin.Forms中的ListView的ObservableCollection

[英]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.

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