具有Stack结构的JSON反序列化可以颠倒顺序 [英] JSON deserialization with Stack structure reverses order
本文介绍了具有Stack结构的JSON反序列化可以颠倒顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用NewtonSoft JSO序列化程序和堆栈数据结构.反序列化结构时,顺序相反.比较数字和ss.
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);
}
}
}
推荐答案
有一个简单的解决方法,但要花费一些额外的处理时间.反序列化为List
,将其反序,然后将其填充到堆栈中.
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);
}
这篇关于具有Stack结构的JSON反序列化可以颠倒顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文