存储序列化和反序列化的序列化相关的信息的最佳方式 [英] Best way to store serialization related info between serialization and deserialization
问题描述
我使用的是序列化的DataContractSerializer
并保存如对象,它有场字典<字符串,IKnownTypesProvider>
,其中 IKnownTypesProvider
只知道哪种类型的它包括从。因此,我可以很容易地使用它来序列化现有的对象。但是,如果我想反序列化后,我有已知类型的列表传递给的DataContractSerializer
但我不能这样做,因为我不知道哪种类型的人使用时,该对象被序列化。从MSDN SUP preSS这个问题的所有合成样品只需通过序列化和反序列化对象以相同的方法,因此具有相同的一组已知的类型。您能否提供一个方法来绕过它?或者,也许你可以建议序列化/反序列化的另一种机制,没有这样的问题呢?
I'm using serialization with DataContractSerializer
and have to save e.g. object which has field of Dictionary<string, IKnownTypesProvider>
where IKnownTypesProvider
just know which types does it consist from. So I can easily use it to serialize existing object. But if I want to deserialize it later I have to pass a list of known types to DataContractSerializer
but I can't do it because I don't know which types were used when that object was serialized. All synthetic samples from MSDN suppress this issue just by serializing and deserializing object in the same method thus having the same set of known types. Can you suggest a way to bypass it? Or maybe you can suggest another mechanism of serialization/deserialization which doesn't have such problem?
UPD:@ I4V建议使用Json.NET。但这里是我的例子,它失败。 忘了我最初的code。下面是示例:
UPD: @I4V suggested to use Json.NET. However here is my example where it fails. Forget about my initial code. Here is the sample:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace TestConsoleProject
{
internal class Program
{
private static void Main(string[] args)
{
var external = new External();
external.Dictionary.Add(100, new Internal() {InternalCount = 100});
external.Dictionary.Add(200, new DerivedInternal() {InternalCount = 200, DerivedInternalCount = 200});
var settings = new JsonSerializerSettings() {TypeNameHandling = TypeNameHandling.All};
var json = JsonConvert.SerializeObject(external, settings);
Console.WriteLine(json);
var otherExternal = JsonConvert.DeserializeObject<External>(json);
Console.WriteLine(otherExternal.Dictionary[200].GetType());
Console.ReadLine();
}
private class External
{
public Dictionary<int, Internal> Dictionary { get; set; }
public External()
{
Dictionary = new Dictionary<int, Internal>();
}
}
private class Internal
{
public int InternalCount { get; set; }
}
private class DerivedInternal : Internal
{
public int DerivedInternalCount { get; set; }
}
}
}
你可以看到,在字典中的第二个对象序列化为 DerivedInternal
(这是正确的),但反序列化只是内部从而丢失数据,我需要。我可以修复它,无论如何?
}
You can see that the second object in dictionary is serialized as DerivedInternal
(which is right) but deserialized as just Internal thus loosing data I need. Can I fix it anyhow?
推荐答案
您可以使用 Json.Net 一>
var settings = new JsonSerializerSettings() {
TypeNameHandling = TypeNameHandling.All };
var json = JsonConvert.SerializeObject(obj, settings);
var newObj = JsonConvert.DeserializeObject<SomeType>(json, settings);
这篇关于存储序列化和反序列化的序列化相关的信息的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!