JSON deserialization with Stack structure reverses order

1.2k views Asked by At

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 are 1 answers

0
Brian On

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