简体   繁体   中英

Parse JSON API from Dictionary to ObservableCollection for ListView in Xamarin.Forms

I am trying to Parse an API endpoint with errors.

This is the raw JSON returning from API

{"posts":{"29.11.2018":[{"title":"xxx","image_url":null,"message":"xxxx","time":"08:30 AM"}]}

This is my 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; }
    }

My service class

var notification = JsonConvert.DeserializeObject<Dictionary<string, Notification>>(apiContent); //Deserialize the JSON data
var _schoolNotification = new ObservableCollection<Post>(notification.Keys);
NotificationListView.ItemsSource = _schoolNotification;

My Edited XAML

<StackLayout>
    <Label Style="{StaticResource ListViewTitle}" Text="{Binding title}" />
   <Label Text="{Binding message}" TextColor="{DynamicResource ListViewDateColor}" />
</StackLayout>

The issue i am facing is, i cant parse this Dictionary to a ObservableColection to be used by Xamarin.Forms.

Any help will be appreciated.

i think that the previews answer was right but need casting so try this

//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);

I suggest running your JSON response through jsonutils.com and using that generated class as the model in the deserialization step. It's usually fool proof and removes the potential human error when trying to manually define the classes.

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