【问题标题】:JSON deserialization with Stack structure reverses order [duplicate]具有堆栈结构的 JSON 反序列化反转顺序 [重复]
【发布时间】:2015-09-10 21:59:30
【问题描述】:

使用 NewtonSoft JSO 序列化程序和堆栈数据结构。当我反序列化结构时,顺序是相反的。比较数字和 ss。

我在这里做错了什么还是有任何解决方法。

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

    }
}

【问题讨论】:

    标签: c# json stack json.net json-deserialization


    【解决方案1】:

    有一个简单的解决方法,但会花费一些额外的处理时间。反序列化为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);
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-21
      • 1970-01-01
      • 1970-01-01
      • 2014-11-02
      • 1970-01-01
      • 1970-01-01
      • 2021-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多