2015-06-24 47 views
4

使用NewtonSoft JSO串行器和堆棧數據結構。當我對結構進行反序列化時,順序相反。比較數字和ss。使用Stack結構的JSON反序列化顛倒順序

我在這裏做錯了什麼,或者是否有任何解決方法的問題。

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

    } 
} 

回答

0

有一個簡單的解決方法,以一些額外的處理時間爲代價。反序列化爲List,將其反轉,然後用它填充堆棧。

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