XmlSerializer-Hubo un error que reflejaba el tipo


Usando C#. NET 2.0, tengo una clase de datos compuestos que tiene el atributo [Serializable]. Estoy creando una clase XMLSerializer y pasándola al constructor:

XmlSerializer serializer = new XmlSerializer(typeof(DataClass));

Estoy recibiendo una excepción diciendo:

Hubo un error que reflejaba el tipo.

Dentro de la clase data hay otro objeto compuesto. ¿Esto también necesita tener el atributo [Serializable], o al tenerlo en el objeto superior, lo aplica recursivamente a todos los objetos dentro?

Author: Ryan Kohn, 2008-09-13

16 answers

Mira la excepción interna que estás recibiendo. Le dirá qué campo / propiedad está teniendo problemas para serializar.

Puede excluir campos/propiedades de la serialización xml decorándolos con el atributo [XmlIgnore].

No creo que XmlSerializer use el atributo [Serializable], así que dudo que ese sea el problema.

 389
Author: Lamar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-11 08:06:59

Recuerde que las clases serializadas deben tener constructores predeterminados (es decir, sin parámetros). Si no tienes ningún constructor, está bien; pero si tienes un constructor con un parámetro, necesitarás agregar el predeterminado también.

 107
Author: Jeremy McGee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-13 16:23:20

Tuve un problema similar, y resultó que el serializador no podía distinguir entre 2 clases que tenía con el mismo nombre (una era una subclase de la otra). La excepción interna se veía así:

'Tipos BaseNamespace.Class1 ' y ' BaseNamespace.SubNamespace.Class1 'ambos usan el nombre de tipo XML, 'Class1', from namespace ". Utilice los atributos XML para especificar un nombre XML único y/o un espacio de nombres para el tipo.

Donde BaseNamespace.SubNamespace.Class1 es una subclase de BaseNamespace.Clase 1.

Lo que necesitaba hacer era agregar un atributo a una de las clases (agregué a la clase base):

[XmlType("BaseNamespace.Class1")]

Nota: Si tiene más capas de clases, también debe agregarles un atributo.

 21
Author: Dennis Calla,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-16 21:51:10

También tenga en cuenta que XmlSerializer no puede serializar propiedades abstractas.. Vea mi pregunta aquí (a la que he agregado el código de solución)..

Serialización XML y Tipos Heredados

 7
Author: Rob Cooper,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:51

Razones Más comunes por mí:

 - the object being serialized has no parameterless constructor
 - the object contains Dictionary
 - the object has some public Interface members
 6
Author: Stefan Michev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-22 12:43:26

Todos los objetos en el gráfico de serialización tienen que ser serializables.

Dado que XMLSerializer es una caja negra, marque estos enlaces si desea depurar más en el proceso de serialización..

Cambiar el lugar donde XmlSerializer Produce Conjuntos Temporales

CÓMO: Depurar en un ensamblado generado por. NET XmlSerializer

 5
Author: Gulzar Nazim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-05 14:34:06

Si necesita manejar atributos específicos (es decir, Diccionario, o cualquier clase), puede implementar la interfaz IXmlSerialiable, que le permitirá más libertad a costa de una codificación más detallada.

public class NetService : IXmlSerializable
{
    #region Data

        public string Identifier = String.Empty;

        public string Name = String.Empty;

        public IPAddress Address = IPAddress.None;
        public int Port = 7777;

    #endregion

    #region IXmlSerializable Implementation

        public XmlSchema GetSchema() { return (null); }

        public void ReadXml(XmlReader reader)
        {
            // Attributes
            Identifier = reader[XML_IDENTIFIER];
            if (Int32.TryParse(reader[XML_NETWORK_PORT], out Port) == false)
            throw new XmlException("unable to parse the element " + typeof(NetService).Name + " (badly formatted parameter " + XML_NETWORK_PORT);
            if (IPAddress.TryParse(reader[XML_NETWORK_ADDR], out Address) == false)
            throw new XmlException("unable to parse the element " + typeof(NetService).Name + " (badly formatted parameter " + XML_NETWORK_ADDR);
        }

        public void WriteXml(XmlWriter writer)
        {
            // Attributes
            writer.WriteAttributeString(XML_IDENTIFIER, Identifier);
            writer.WriteAttributeString(XML_NETWORK_ADDR, Address.ToString());
            writer.WriteAttributeString(XML_NETWORK_PORT, Port.ToString());
        }

        private const string XML_IDENTIFIER = "Id";

        private const string XML_NETWORK_ADDR = "Address";

        private const string XML_NETWORK_PORT = "Port";

    #endregion
}

Hay un interesante artículo , que muestra una forma elegante de implementar una forma sofisticada de "extender" el XmlSerializer.


El artículo dice:

IXmlSerializable está cubierto en la documentación oficial, pero el la documentación indica que no está destinada al uso público y no proporciona información más allá de eso. Esto indica que el equipo de desarrollo quería reservarse el derecho de modificar, deshabilitar o incluso eliminar por completo este gancho de extensibilidad en el futuro. Sin embargo, mientras estés dispuesto a aceptar esta incertidumbre y lidiar con posibles cambios en el futuro, no hay razón alguna para que no puedas aprovecharla.

Debido a esto, sugiero implementar tus propias clases IXmlSerializable, para evitar implementaciones demasiado complicadas.

Could podría ser sencillo implementar nuestra clase personalizada XmlSerializer usando reflexión.

 5
Author: Luca,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-01 08:02:09

He descubierto que la clase Dictionary en.Net 2.0 no es serializable usando XML, pero se serializa bien cuando se usa la serialización binaria.

Encontré un trabajo alrededor de aquí.

 4
Author: Charlie Salts,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-02 19:32:19

Recientemente obtuve esto en una clase parcial de referencia web al agregar una nueva propiedad. La clase generada automáticamente agregaba los siguientes atributos.

    [System.Xml.Serialization.XmlElementAttribute(Order = XX)]

Necesitaba agregar un atributo similar con un orden más alto que el último en la secuencia generada automáticamente y esto lo arregló para mí.

 3
Author: LepardUK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-17 14:15:18

Yo también pensé que el atributo Serializable tenía que estar en el objeto, pero a menos que esté siendo un novato completo (estoy en medio de una sesión de codificación nocturna), lo siguiente funciona desde el SnippetCompiler :

using System;
using System.IO;
using System.Xml;
using System.Collections.Generic;
using System.Xml.Serialization;

public class Inner
{
    private string _AnotherStringProperty;
    public string AnotherStringProperty 
    { 
      get { return _AnotherStringProperty; } 
      set { _AnotherStringProperty = value; } 
    }
}

public class DataClass
{
    private string _StringProperty;
    public string StringProperty 
    { 
       get { return _StringProperty; } 
       set{ _StringProperty = value; } 
    }

    private Inner _InnerObject;
    public Inner InnerObject 
    { 
       get { return _InnerObject; } 
       set { _InnerObject = value; } 
    }
}

public class MyClass
{

    public static void Main()
    {
        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(DataClass));
            TextWriter writer = new StreamWriter(@"c:\tmp\dataClass.xml");
            DataClass clazz = new DataClass();
            Inner inner = new Inner();
            inner.AnotherStringProperty = "Foo2";
            clazz.InnerObject = inner;
            clazz.StringProperty = "foo";
            serializer.Serialize(writer, clazz);
        }
        finally
        {
            Console.Write("Press any key to continue...");
            Console.ReadKey();
        }
    }

}

Me imagino que el XmlSerializer está usando reflexión sobre las propiedades públicas.

 2
Author: Darren,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-13 15:23:04

Tuve una situación en la que el Orden era el mismo para dos elementos en una fila

[System.Xml.Serialization.XmlElementAttribute(IsNullable = true, Order = 0, ElementName = "SeriousInjuryFlag")]

.... algún código ...

[System.Xml.Serialization.XmlElementAttribute(IsNullable = true, Order = 0, ElementName = "AccidentFlag")]

Cuando cambié el código para incrementar el orden en uno para cada nueva Propiedad en la clase, el error desapareció.

 1
Author: Jeremy Brown,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-10 10:57:44

Acabo de recibir el mismo error y descubrí que una propiedad de tipo IEnumerable<SomeClass> era el problema. Parece que IEnumerable no puede ser serializado directamente.

 1
Author: jkokorian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-05 14:35:25

También tenga en cuenta que no puede serializar los controles de la interfaz de usuario y que cualquier objeto que desee pasar al portapapeles debe ser serializable de lo contrario no se puede pasar a otros procesos.

 0
Author: Phil Wright,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-13 14:55:17

He estado usando la clase NetDataSerialiser para serializar mis clases de dominio. NetDataContractSerializer Class.

Las clases de dominio se comparten entre cliente y servidor.

 0
Author: Peter Mortensen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-22 12:27:07

[Sistema.XML.Serialización.XmlElementAttribute ("strFieldName", Form = System.XML.Esquema.XmlSchemaForm.Sin reservas)]

//O

[XmlIgnore] string [] strFielsName {get; set;}

 0
Author: Kiran.Bakwad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-16 11:48:17

Tuve el mismo problema y en mi caso el objeto tenía una ReadOnlyCollection. Una colección debe implementar el método Add para ser serializable.

 0
Author: Curious Dev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-26 01:19:58