使用堆栈结构进行JSON反序列化可以颠倒顺序

6
使用NewtonSoft JSO序列化器和堆栈数据结构。当我反序列化结构时,顺序会被颠倒。比较数字和字符串。
这里我做错了什么或者是否有解决该问题的方法?
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

class Example
{
    public static void Main()
    {
        Stack<string> numbers = new Stack<string>();
        numbers.Push("one");
        numbers.Push("two");
        numbers.Push("three");
        numbers.Push("four");
        numbers.Push("five");

         string json = JsonConvert.SerializeObject(numbers.ToArray() );

        // A stack can be enumerated without disturbing its contents. 
        foreach (string number in numbers)
        {
            Console.WriteLine(number);
        }

        Console.WriteLine("\nPopping '{0}'", numbers.Pop());
        Console.WriteLine("Peek at next item to destack: {0}",
            numbers.Peek());
        Console.WriteLine("Popping '{0}'", numbers.Pop());

        Stack<string> ss = null;
        if (json != null)
        {
            ss = JsonConvert.DeserializeObject<Stack<string>>(json);
        } 

    }
}
1个回答

3

有一个简单的解决办法,但需要额外的处理时间。将其反序列化为List,然后将其颠倒顺序并用栈来填充。

List<string> ls = null;
Stack<string> ss = null;
if (json != null)
{
    ls = JsonConvert.DeserializeObject<List<string>>(json);
    ls.Reverse();
    ss = new Stack<string>(ls);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接