Я сериализовал класс с кодом:
public void Save()
{
string fichero = Application.persistentDataPath + "/" + nombreJuego + ".dat";
FileStream file = File.Create(fichero);
DataContractSerializer bf = new DataContractSerializer(typeof(JuegoMesa));
MemoryStream streamer = new MemoryStream();
bf.WriteObject(streamer, this);
streamer.Seek(0, SeekOrigin.Begin);
file.Write(streamer.GetBuffer(), 0, streamer.GetBuffer().Length);
file.Close();
}
и десериализуйте его с помощью:
public void Load()
{
string fichero = Application.persistentDataPath + "/" + nombreJuego + ".dat";
Debug.Log(fichero);
DataContractSerializer bf = new DataContractSerializer(typeof(JuegoMesa));
try
{
JuegoMesa leido = null;
object objeto;
MemoryStream streamer = new MemoryStream(File.ReadAllBytes(fichero));
streamer.Seek(0, SeekOrigin.Begin);
objeto = bf.ReadObject(streamer);
leido = (JuegoMesa)objeto;
ActualizarListas(leido.listaListas);
ActualizarPropiedades(leido.listaPropiedades);
ActualizarRecursos(leido.listaRecursos);
ActualizarComponentes(leido.listaComponentes);
}
catch (FileNotFoundException)
{
listaListas.Clear();
listaPropiedades.Clear();
listaRecursos.Limpiar();
listaComponentes.Clear();
Save();
}
}
При чтении объект дает мне исключение:
XmlException: Type not found; name: PropiedadTexto, namespace: http://schemas.datacontract.org/2004/07/ System.Runtime.Serialization.XmlFormatterDeserializer.GetTypeFromNamePair (System.String name, System.String ns)
Класс имеет следующие элементы для сериализации:
public string nombreJuego;
public List<TextosPredefinidos> listaListas;
public List<Propiedad> listaPropiedades;
public ListaRecursos listaRecursos;
public List<ListaRecursos> listaComponentes;
В
List<Propiedad>
представляет собой список объектов классов, производных от класса Propiedad. На примере класса с ошибкой
[Serializable]
public class PropiedadTexto : Propiedad
{
public string textoDescriptivo;
public PropiedadTexto() : base()
{
}
...
}
Кто-нибудь знает, в чем может быть проблема?
Прошу прощения за мой плохой английский.
Спасибо.
Не могли бы вы, пожалуйста, редактировать ваш вопрос, чтобы поделиться минимальный воспроизводимый пример, который воспроизводит проблему? Мы с большей вероятностью сможем помочь, если сможем самостоятельно протестировать и отладить проблему; см. Как спросить для получения дополнительной информации.





Пытаясь создать минимальный / полный / проверяемый пример, я нашел решение. Я до сих пор не понимаю, почему он выдает ошибку, но решение - создать класс, производный от DataContractResolver, и сообщить неизвестные типы
class ResolverXml : DataContractResolver
{
private XmlDictionary dictionary = new XmlDictionary();
public ResolverXml()
{
}
public override bool TryResolveType(Type dataContractType, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
{
if (dataContractType == typeof(PropiedadTexto))
{
XmlDictionary dictionary = new XmlDictionary();
typeName = dictionary.Add("PropiedadTexto");
typeNamespace = dictionary.Add("JuegoMesa");
return true;
}
else
{
return knownTypeResolver.TryResolveType(dataContractType, declaredType, null, out typeName, out typeNamespace);
}
}
// public override Type ResolveName(string typeName, string typeNamespace, DataContractResolver knownTypeResolver)
public override Type ResolveName(string typeName, string typeNamespace, Type type, DataContractResolver knownTypeResolver)
{
if (typeName == "PropiedadTexto" && typeNamespace == "JuegoMesa")
{
return typeof(PropiedadTexto);
}
else
{
return knownTypeResolver.ResolveName(typeName, typeNamespace, type, null);
}
}
}
и это должно быть указано в конструкторе DataContractSerializer
DataContractSerializer bf = new DataContractSerializer(typeof(PruebaXml), null, Int32.MaxValue, false, false, null, new ResolverXml());
Но единство не распознает класс DataContractResolver. Альтернативный вариант заключался в том, чтобы сообщить неизвестные типы в конструкторе DataContractSerializer.
private List<Type> tiposConocidos;
tiposConocidos.Add(typeof(PropiedadTexto));
tiposConocidos.Add(typeof(PropiedadEntero));
DataContractSerializer bf = new DataContractSerializer(typeof(JuegoMesa), tiposConocidos);
Я подозреваю, что версия кода при использовании сериализатора и десериализатора отличается. Кто-то изменил одни классы и либо добавил / удалил свойство.