JsonConvert.Deserializer indexing issues

后端 未结 4 613
情话喂你
情话喂你 2020-11-29 14:07

While playing around Stack collection in C# I encountered the following issue. Exactly I am not sure why it is happening. Please put some light on the reason and alternative

4条回答
  •  情深已故
    2020-11-29 14:13

    It seems like the stack is being serialized as a List. The problem is that this does not preserve the proper order when deconstructing the stack (the items are actually pushed in the reverse order). Here's a quick workaround to this issue:

    using System;
    using static System.Console;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using Newtonsoft.Json;
    
    namespace StackCollection
    {
        class Program
        {
            static void Main(string[] args)
            {
                Progress progress = new Progress();
    
                progress.Items.Push(new Item { PlanID = null, PlanName = "Plan A" });
    
                var jsonString = JsonConvert.SerializeObject(progress);
                var temp = JsonConvert.DeserializeObject(jsonString);
    
                temp.Items.Push(new Item { PlanID = null, PlanName = "Plan B" });
    
                jsonString = JsonConvert.SerializeObject(temp);
                temp = JsonConvert.DeserializeObject(jsonString);
    
                temp.Items.Push(new Item { PlanID = null, PlanName = "Plan C" });
    
                jsonString = JsonConvert.SerializeObject(temp);
                temp = JsonConvert.DeserializeObject(jsonString);
    
                WriteLine(temp.Items.Peek().PlanName);
    
                ReadLine();
            }
        }
    
        class Progress
        {
            [JsonIgnore]
            public Stack Items { get; set; }
    
            public List ItemList { get; set; }
    
            [OnSerializing]
            internal void OnSerializing(StreamingContext context)
            {
                ItemList = Items?.ToList();
            }
    
            [OnDeserialized]
            internal void OnDeserialized(StreamingContext context)
            {
                ItemList?.Reverse();
                Items = new Stack(ItemList ?? Enumerable.Empty());
            }
    
            public Progress()
            {
                Items = new Stack();
            }
        }
    
        class Item
        {
            public string PlanID { get; set; }
    
            public string PlanName { get; set; }
        }
    }
    

提交回复
热议问题