c# - JSON反序列化Stack结构颠倒顺序

标签 c# json stack json.net json-deserialization

<分区>

使用 NewtonSoft JSO 序列化程序和堆栈数据结构。当我反序列化结构时,顺序被颠倒了。比较数字和 ss。

我是不是做错了什么,或者是否有任何解决方法。

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

    }
}

最佳答案

有一个简单的解决方法,但需要一些额外的处理时间。反序列化为 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);
}

关于c# - JSON反序列化Stack结构颠倒顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31030973/

相关文章:

json - Flutter/Dart Json序列化

c++ - main()是用一个自动变量创建的,如果是,它的用途是什么?

c# - Windows Phone Live SDK API - 重新启动应用程序后获取新的 session 对象

c# - 如何从用户输入 C# 填充数组?

c# - 如何在 PropertyGrid 中使用 NodaTime 类?

c# - 委托(delegate):Predicate vs. Action vs. Func

jquery - Rails,发送 json 参数

jquery - 自定义节点图标在 Fancytree 中不起作用

android - 如何让我的应用程序始终位于任务堆栈的顶部?

python - 为什么 Python 有最大递归深度?