我有一個具有Queue類型屬性的類。當嘗試反序列化JSON的,我得到以下錯誤:使用隊列反序列化一個類<T>使用Newtonsoft.Json
Type specified in JSON 'ConsoleApplication1.Task[], ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not compatible with 'System.Collections.Generic.Queue`1[[ConsoleApplication1.Task, ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Path 'Tasks.$type', line 1, position 140.
我已經包含下面的示例應用程序,我使用Newtonsoft.Json 4.5.10.15407。
我使用隊列而不是列表或詞典的原因是因爲我必須保留插入順序。我也嘗試過搜索文檔和其他問題,但還沒有真正找到具體的東西。任何幫助深表感謝。謝謝。
namespace ConsoleApplication1
{
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
class Program
{
static void Main(string[] args)
{
Message message = new Message
{
MessageID = 1,
Tasks = new Queue<Task>()
};
message.Tasks.Enqueue(new Task{TaskId = 1, Message = "Test1", Parameters = "Param1"});
message.Tasks.Enqueue(new Task{TaskId = 2, Message = "Test2", Parameters = "Param2"});
byte[] bSerialized = SerializeJsonWithPrefix(message);
Message deserializedMessage = DeserializeJson(bSerialized, typeof (Message));
}
public static byte[] SerializeJsonWithPrefix(Message item)
{
JsonSerializerSettings jss = new JsonSerializerSettings();
jss.TypeNameHandling = TypeNameHandling.All;
return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(item, jss));
}
public static Message DeserializeJson(byte[] ueaData, Type concreteType)
{
JsonSerializerSettings jss = new JsonSerializerSettings();
jss.TypeNameHandling = TypeNameHandling.All;
// --- Error occurs here ---
var result = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(ueaData), concreteType, jss);
return (Message)result;
}
}
public class Message
{
public int MessageID { get; set; }
public Queue<Task> Tasks { get; set; }
}
public class Task
{
public int TaskId { get; set; }
public string Message { get; set; }
public string Parameters { get; set; }
}
}