使用Newtonsoft.Json序列化和反序列化后,堆栈元素的顺序颠倒

本文关键字:栈元素 堆栈 顺序 Json Newtonsoft 序列化 反序列化 使用 | 更新日期: 2023-09-27 18:06:53

我在序列化/反序列化时遇到堆栈中元素顺序颠倒的问题。

的示例
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace StackChecker
{
    class Program
    {
        enum Screen
        {
           Unknown,
           Bypass,
           ClaimDetails,
           ClaimSearch,
           ClaimSearchResults,
           PatientSearchResults
        }
        static void Main(string[] args)
        {
            var screens = new Stack<Screen>();
            screens.Push(Screen.Unknown);
            screens.Push(Screen.Bypass);
            screens.Push(Screen.ClaimDetails);
            screens.Push(Screen.ClaimSearch);
            screens.Push(Screen.ClaimSearchResults);
            screens.Push(Screen.PatientSearchResults);
            foreach (var screen in screens)
            {
                Console.WriteLine("Screen {0}: {1}", (int)screen, screen);
            }
            var screenJson = JsonConvert.SerializeObject(screens);
            Console.WriteLine("Screens Json: '"{0}'"", screenJson);
            var screens2 = JsonConvert.DeserializeObject<Stack<Screen>>(screenJson);
            foreach (var screen in screens2)
            {
                Console.WriteLine("Screen {0}: {1}", (int)screen, screen);
            }
            var screenJson2 = JsonConvert.SerializeObject(screens2);
            Console.WriteLine("Screens Json: '"{0}'"", screenJson2);
            Console.ReadLine();
        }
    }
}

输出如下内容:

Screen 5: PatientSearchResults
Screen 4: ClaimSearchResults
Screen 3: ClaimSearch
Screen 2: ClaimDetails
Screen 1: Bypass
Screen 0: Unknown
Screens Json: "[5,4,3,2,1,0]"
Screen 0: Unknown
Screen 1: Bypass
Screen 2: ClaimDetails
Screen 3: ClaimSearch
Screen 4: ClaimSearchResults
Screen 5: PatientSearchResults
Screens Json: "[0,1,2,3,4,5]"

那么,问题是-为什么顺序颠倒了?(我也尝试过这个数组,可以证明数组元素不反转)

这可以避免吗?
如果没有,谁有一个优雅的解决方案的想法?

使用Newtonsoft.Json序列化和反序列化后,堆栈元素的顺序颠倒

可以反序列化为var screens2 = JsonConvert.DeserializeObject<List<Screen>>(screenJson)之类的List。如果你需要一个堆栈作为数据结构,那么你可以创建一个临时列表,并将其反向复制到堆栈中。

var screensTemp = JsonConvert.DeserializeObject<List<Screen>>(screenJson);
screensTemp.Reverse();
var screens2 = new Stack<Screen>(screensTemp);
foreach (var screen in screens2)
{
    Console.WriteLine("Screen {0}: {1}", (int)screen, screen);
}