JSON deserialization with Stack structure reverses order [duplicate]

扶醉桌前 提交于 2021-01-02 11:40:09

问题


Using the NewtonSoft JSO serializer and a stack data structure. The order is reversed when I deserialize the structure. Comparing numbers and ss.

Am I doing something wrong here or is there any workaround the issue.

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:


There is a simple workaround, at the cost of some extra processing time. Deserialize into a List, reverse it, and then fill a stack with that.

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


来源:https://stackoverflow.com/questions/31030973/json-deserialization-with-stack-structure-reverses-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!