Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON deserialization with Stack structure reverses order [duplicate]

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

    }
}
like image 965
user3502865 Avatar asked Jun 24 '15 15:06

user3502865


1 Answers

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);
}
like image 183
Brian Avatar answered Nov 04 '22 20:11

Brian