Best way to store serialization related info between serialization and deserialization

China☆狼群 提交于 2020-01-06 14:59:24

问题


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

} 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?


回答1:


You can use Json.Net

var settings = new JsonSerializerSettings() { 
                     TypeNameHandling = TypeNameHandling.All };

var json = JsonConvert.SerializeObject(obj, settings);
var newObj = JsonConvert.DeserializeObject<SomeType>(json, settings);


来源:https://stackoverflow.com/questions/18400956/best-way-to-store-serialization-related-info-between-serialization-and-deseriali

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!