0
votes

I get this error The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.

Unexpected type 'A' with data contract name 'A: http://schemas.datacontract.org/2004/07/' . If you are using DataContractSerializer, try using DataContractResolver or add types not known statically to the list of known types (for example, using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer).

when serializing an object with a property that can be 2 types A or B.

xsd.exe generated the object like this:

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class Doc
{    
    [XmlElement("A", typeof(A))]
    [XmlElement("B", typeof(B))]
    [System.Xml.Serialization.XmlTextAttribute(typeof(string))]
    public object Item { get; set; }
}

Type A and B are defined too, just normal classes with 1 property.

and I initialize the object like this

Doc d = new Doc();

var i = new A
{
    Id = 1,
};

doc.Item = i;

which compiles fine, but when it tries to serialize it throws the error mentioned above

1
And can you please include the serializer code? - Glen Thomas
You are marking your class with XmlSerializer attributes but your exception was generated by DataContractSerializer, a completely different serializer that uses different attributes. You need to use svcutil.exe to generate classes for it. - dbc
This is an mvc project, do I still have to use scvutil.exe ? I only have an xsd - Renato Herrera
I think if you show us the serializer code the picture will be a lot clearer - Glen Thomas
How do I change the Asp.Net MVC to user xmlserializer instead of the datacontractseriallizer? - Renato Herrera

1 Answers

0
votes

I think you might need a common base class where you can specify known types:

[KnownType(typeof(A))]
[KnownType(typeof(B))]
public class AorB
{
    public int Id {get;set;}
}

public class A : AorB
{
}

public class B : AorB
{
}

then in doc class:

public partial class Doc
{    
    public AorB Item { get; set; }
}

Alternatively, if you are using DataContractSerializer, you can pass an IEnumerable of known types into the constructor:

var serializer = new DataContractSerializer(typof(Doc), new[] { typeof(A), typeof(B) });