Set accessor not being called when I deserialise object from Json.net

后端 未结 1 503
眼角桃花
眼角桃花 2020-12-21 06:23
public class SpecialObject
{
    public string ID;
    [JsonIgnore]
    public List SpecialObjectCollection = new List();
          


        
相关标签:
1条回答
  • 2020-12-21 06:37

    Your problem is that, when deserializing a collection that is not read-only, Json.NET checks to see if the collection has already been allocated, for instance in the constructor of the containing type. If so, it fills the pre-existing collection for the deserialized JSON contents, and never sets the collection back. Unfortunately, your property returns a temporary proxy collection, so your container class SpecialObject never receives the deserialized results.

    The simplest way to prevent this is to specify that Json.NET should always allocate a new collection and set it back rather than reuse the pre-existing collection, via the JsonPropertyAttribute setting ObjectCreationHandling = ObjectCreationHandling.Replace

    [JsonProperty(ObjectCreationHandling = ObjectCreationHandling.Replace)]
    public List<string> SpecialObjectIDs { get { return SpecialObjectCollection.Select(x => x.ID).ToList(); } set { tempObjectIDs = value; } }
    

    Alternatively you could use a string [] rather than a List<string> for your proxy collection property:

    public string [] SpecialObjectIDs { get { return SpecialObjectCollection.Select(x => x.ID).ToArray(); } set { tempObjectIDs = value == null ? null : value.ToList(); } }
    

    As arrays cannot be resized, Json.NET will always allocate a new array when deserializing and set it back when complete.

    0 讨论(0)
提交回复
热议问题