使用Newtonsoft.Json进行序列化和反序列化后,堆栈元素的顺序会反转

时间:2016-09-13 12:54:09

标签: c# json.net

在序列化/反序列化时,我对堆栈中元素的顺序有问题。请参阅此演示以了解repro:

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]"

所以,问题是 - 为什么订单被撤销了? (我也用数组试过这个,可以证明数组元素没有反转)

可以避免吗?
如果没有,任何人都有一个优雅的解决方法的想法?

1 个答案:

答案 0 :(得分:1)

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

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