0

Имеется довольно сложная структура следующего вида:

[Serializable]
public class A
{
    public int a1 {get;set;}
    public bool a2 { get; set; }
    public string a3 { get; set; }
    .......
}

[Serializable]
public class B
{
    public int b1 { get; set; }
    public bool b2 { get; set; }
    public string b3 { get; set; }

    public List<A> ba1 { get; set; }

    public List<string> ba2 { get; set; }
    ......
}

Третий день бьюсь над XML сериализацией класса B.

Выдает ошибку

'Тип "SLib.AccountCfg" с именем контракта данных "AccountCfg:http://schemas.datacontract.org/2004/07/SLib" не ожидается. Попробуйте использовать DataContractResolver, если вы используете DataContractSerializer, или добавьте любые статически неизвестные типы в список известных типов - например, используя атрибут KnownTypeAttribute или путем их добавления в список известных типов, передаваемый в сериализатор.'

Сама процедура сериализации

    public void Save(PhoneCfg inConfig)
    {
        XmlTextWriter xw = new XmlTextWriter("Sets.xml", Encoding.UTF8);
        xw.Formatting = Formatting.Indented;
        XmlDictionaryWriter writer = 
        XmlDictionaryWriter.CreateDictionaryWriter(xw);
        DataContractSerializer ser = new 
        DataContractSerializer(typeof(PhoneCfg));
        ser.WriteObject(writer, inConfig);
        writer.Close();
        xw.Close();
    }

Что я делаю не так?


Реально это файлы настройки SIP-телефонии

[Serializable]
public class AccountCfg : IAccount
{
    public AccountCfg() { }

    public int Index { get; set; }
    public string AccountName { get; set; }
    public string HostName { get; set; }
    public string Id { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public string DisplayName { get; set; }
    public string DomainName { get; set; }
    public int RegState { get; set; }
    public string ProxyAddress { get; set; }
    public ETransportMode TransportMode { get; set; }

    public bool Enabled { get; set; }

    public override string ToString()
    {
        return Id;
    }
}

[Serializable]
public class PhoneCfg : IConfiguratorInterface
{
    private List<IAccount> m_Accounts;
    private int m_DefaultAccountIndex=0;
    private bool m_IsNull;

    public PhoneCfg()
    {
    }

    public bool DNDFlag { get; set; }
    public bool AAFlag { get; set; }
    public bool CFUFlag { get; set; }
    public string CFUNumber { get; set; }
    public bool CFNRFlag { get; set; }
    public string CFNRNumber { get; set; }
    public bool CFBFlag { get; set; }
    public string CFBNumber { get; set; }
    public int SIPPort { get; set; }
    public int DefaultAccountIndex { get => m_DefaultAccountIndex; set => m_DefaultAccountIndex = value; }
    public List<string> CodecList { get; set; }
    public bool PublishEnabled { get; set; }
    public List<IAccount> Accounts { get => m_Accounts; set => m_Accounts = value; }
    public bool IsNull { get => m_IsNull; set => m_IsNull = value; }

    public string StunServerAddress { get; set; }
    public EDtmfMode DtmfMode { get; set; }
    public int iDtmfMode { get; set; }
    public int Expires { get; set; }
    public int ECTail { get; set; }
    public bool VADEnabled { get; set; }
    public string NameServer { get; set; }
    public int defaultATime { get; set; }

    public void Save()
    {
    }
}
4
  • Сама процедура сериализации public void Save(PhoneCfg inConfig) { XmlTextWriter xw = new XmlTextWriter("Sets.xml", Encoding.UTF8); xw.Formatting = Formatting.Indented; XmlDictionaryWriter writer = XmlDictionaryWriter.CreateDictionaryWriter(xw); DataContractSerializer ser = new DataContractSerializer(typeof(PhoneCfg)); ser.WriteObject(writer, inConfig); writer.Close(); xw.Close(); } 4 мая 2018 в 1:03
  • А почему так сложно? Почему просто не использовать XmlSerializer? Ну а вообще, у меня лично не удалось воспроизвести вашу проблему, вроде и классы прям скопировал и сериализацию вашу - результат - файл на месте (правда вида ужасного, но это другой вопрос как по мне..)
    – EvgeniyZ
    4 мая 2018 в 1:26
  • Вы показали классы A и B, а сериализуете PhoneCfg. Покажите класс PhoneCfg. 4 мая 2018 в 9:59
  • Почитайте ru.stackoverflow.com/questions/823923/… 7 мая 2018 в 8:43

1 ответ 1

1

Пометьте свой класс атрибутом:

[KnownType(typeof(AccountCfg))]
public class AccountCfg : IAccount

Тогда сериализатор будет знать, какие возможны реальные типы вместо интерфейса в этом свойстве:

public List<IAccount> Accounts

Другой возможный вариант - добавить определения известных типов при создании сериализатора:

var knownTypes = new List<Type> { typeof(AccountCfg) };

var ser = new DataContractSerializer(typeof(PhoneCfg),
    new DataContractSerializerSettings { KnownTypes = knownTypes });

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.