Json.net deserializing list gives duplicate items

前端 未结 4 1268
眼角桃花
眼角桃花 2021-02-18 15:56

I have just started using Newtonsoft.Json (Json.net). In my first simple test, I ran into a problem when deserializing generic lists. In my code sample below I serialize an obje

4条回答
  •  Happy的楠姐
    2021-02-18 16:45

    I encountered a similar issue with a different root cause. I was serializing and deserializing a class that looked like this:

    public class Appointment
    {
        public List Revisions { get; set; }
    
        public AppointmentRevision CurrentRevision
        {
            get { return Revision.LastOrDefault(); }
        }
    
        public Appointment()
        {
            Revisions = new List();
        }
    }
    
    public class AppointmentRevision
    {
        public List Attendees { get; set; }
    }
    

    When I serialized this, CurrentRevision was being serialized too. I'm not sure how, but when it was deserializing it was correctly keeping a single instance of the AppointmentRevision but creating duplicates in the Attendees list. The solution was to use the JsonIgnore attribute on the CurrentRevision property.

    public class Appointment
    {
        public List Revisions { get; set; }
    
        [JsonIgnore]   
        public AppointmentRevision CurrentRevision
        {
            get { return Revision.LastOrDefault(); }
        }
    
        public Appointment()
        {
            Revisions = new List();
        }
    }
    

提交回复
热议问题