Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JsonConvert.DeserializeObject<Stack<T>>/JsonConvert.Serialize(Stack<T) does not work as expected. #971

Closed
rymeskar opened this issue Jul 25, 2016 · 4 comments

Comments

@rymeskar
Copy link

rymeskar commented Jul 25, 2016

When I serialize a Stack of strings, or of anything else for that matter, and then try to deserialize it with the functions mentioned in the headline, I get a stack with reversed order. Is this unexpected behavior an intended feature? Then to get the expected behavior, I would have to write a specific code for handling stack?

Code that revealed this "feature":

var stack = new Stack<string>();
stack.Push("Inserted first, should be popped last");
stack.Push("Inserted last, should be popped first");
var serializedStack = JsonConvert.SerializeObject(stack);
Console.WriteLine(serializedStack);
//["Inserted last, should be popped first","Inserted first, should be popped last"]
stack = JsonConvert.DeserializeObject<Stack<string>>(serializedStack);
serializedStack = JsonConvert.SerializeObject(stack);
Console.WriteLine(serializedStack);
//["Inserted first, should be popped last","Inserted last, should be popped first"]
Console.WriteLine(stack.Pop());
//Inserted first, should be popped last
Console.WriteLine(stack.Pop());
//Inserted last, should be popped first
@JamesNK
Copy link
Owner

JamesNK commented Aug 7, 2016

I'm afraid this is a limition of a Stack. The results returned when it is serialized and the opposite order for when it is deserialized.

@SlimeQ
Copy link

SlimeQ commented Nov 7, 2018

How could this possibly be a limitation of the stack? The library should just convert to a list and reverse it before serializing. Or when deserializing, deserialize first to a list, reverse it, and create a stack from that list

@SlimeQ
Copy link

SlimeQ commented Nov 7, 2018

            HistoryManager.instance.undoStack = new Stack<HistoryItem>(undoStack.Reverse());
            HistoryManager.instance.redoStack = new Stack<HistoryItem>(redoStack.Reverse());

See? Easy as pie.

Don't blame the built-in types, deal with them!

EDIT: Actually the Stack constructor reverses the input stack, so .Reverse() is unnecessary.

@Banyc
Copy link

Banyc commented Oct 11, 2020

This issue has not been fixed even in version 12.0.3. Sad.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants