我有一个Dictionary,我将其序列化到一个二进制文件中,并使用JSON.net从https://json.codeplex.com/
字典可能包含结构对象(字符串、类,甚至列表)。每个类都是[System.Serializable]
在序列化时,我添加了序列化程序。TypeNameHandling=TypeNameHandling.All;以确保反序列化程序具有反序列化字典所需的类型信息。
我无法将其正确反序列化为相同的对象列表,我在容器中只得到JObjects,而不是原始类型。有人能帮我完成这件事吗?
提前感谢;Laurent
更新:
为了获取数据,我使用这两种方法:
public static byte[] SerializeToByteArray<T>(T data)
{
byte[] serializedData = new byte[]{};
using(var stream = new MemoryStream())
{
using (BsonWriter writer = new BsonWriter(stream))
{
JsonSerializer serializer = new JsonSerializer();
serializer.TypeNameHandling = TypeNameHandling.All;
serializer.Serialize(writer, data);
}
return stream.ToArray();
}
}
public static T DeserializeFromByteArray<T>(byte[] serializedData )
{
using (var stream = new MemoryStream(serializedData))
{
using (BsonReader reader = new BsonReader(stream))
{
JsonSerializer serializer = new JsonSerializer();
return (T)serializer.Deserialize<T>( reader );
}
}
}
[System.Serializable]
public class FavoriteLevel
{
public FavoriteLevel(string ID, int TYPE) { id = ID; type = TYPE;}
public string id;
public int type;
}
Dictionary<string,object> dict = new Dictionary<string,object>(1);
List<FavoriteLevel> levels = new List<FavoriteLevel>(1);
levels.Add (new FavoriteLevel("123",FavoriteType.Favorite) );
dict.Add ( "123", levels );
byte[] data = SerializeToByteArray( dict );
Dictionary<string,object> incomingDict = DeserializeFromByteArray<Dictionary<string,object>>( data );
object listBack = incomingDict["123"];
// ERROR: listBack is a Json object and not a List<FavoriteLevel> object
在反序列化和序列化时都需要设置serializer.TypeNameHandling = TypeNameHandling.All
。否则,"$type"
属性将被忽略。
因此:
public static class JsonExtensions
{
public static byte[] SerializeToByteArray<T>(T data, JsonSerializerSettings settings)
{
using (var stream = new MemoryStream())
{
using (var writer = new BsonWriter(stream))
{
JsonSerializer serializer = JsonSerializer.Create(settings);
serializer.Serialize(writer, data);
}
return stream.ToArray();
}
}
public static T DeserializeFromByteArray<T>(byte[] serializedData, JsonSerializerSettings settings)
{
using (var stream = new MemoryStream(serializedData))
{
using (var reader = new BsonReader(stream))
{
JsonSerializer serializer = JsonSerializer.Create(settings);
return (T)serializer.Deserialize<T>(reader);
}
}
}
}
public static class TestClass
{
public static void Test()
{
Dictionary<string, object> dict = new Dictionary<string, object>(1);
List<FavoriteLevel> levels = new List<FavoriteLevel>(1);
levels.Add(new FavoriteLevel("123", 0));
dict.Add("123", levels);
var settings = new JsonSerializerSettings();
settings.TypeNameHandling = TypeNameHandling.All;
byte[] data = JsonExtensions.SerializeToByteArray(dict, settings);
Dictionary<string, object> incomingDict = JsonExtensions.DeserializeFromByteArray<Dictionary<string, object>>(data, settings);
object listBack = incomingDict["123"];
Debug.Assert(listBack.GetType() == levels.GetType()); // No assert.
}
}