无法序列化父对象的子类

时间:2016-06-30 15:43:21

标签: c# xml serialization entity

我正在构建一个服务来从SQL获取数据并将其包装到实体对象中,然后将它们构建为“Payload”以进行搜索并发送到另一个服务。我将有3种不同类型的有效载荷。我将有一个Request对象,它包含一个Header对象和一个RequestPayload对象,RequestPayload包含一个Payload对象列表,这些Payload对象包含我的实体。我的3种类型的Payload每个都包含一些公共属性,但也有一些特定于它们的类型,所以我创建了一个“Payload”对象,它为所有Payload类型之间的每个公共属性都有XmlAttributes。然后,我有另外3个有效负载,每个负载都包含它们的特定属性,但它们都继承了Payload。我想避免创建不同的RequestPayload类型只是为了保存我的不同Payload对象,我想创建一个RequestPayload对象,并且无论它包含什么类型的Payload,都能够对其进行搜索。这就是我设置它的方式,但是在尝试序列化时我遇到了运行时错误。

请求:

public class Request
{
    [XmlElement]
    public RequestHeader RequestHeader { get; set; }

    [XmlElement]
    public RequestPayload RequestPayload { get; set; }
}

RequestPayload:

public class RequestPayload
{
    // used to be lossincurredpayload
    [XmlElement]
    public List<Payload> BOM_Request { get; set; }
}

有效载荷:

public class Payload
{
    [XmlAttribute]
    public int path { get; set; }

    [XmlAttribute]
    public int sequenceNum { get; set; }

    [XmlAttribute]
    public string requestSentDate { get; set; }

    [XmlAttribute]
    public string validationType { get; set; }

    [XmlAttribute]
    public int transactionId { get; set; }

    [XmlAttribute]
    public string decisionType { get; set; }

}

LossIncurredPayload(我的一种特定有效负载类型):

public class LossIncurredPayload : Payload
{
    [XmlElement]
    public List<LossIncurred> BOM_Policy { get; set; }
}

下面是我正在进行序列化的代码。调用Serialize()方法时,我得到以下错误: "The type LossIncurredPayload was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."

[XmlInclude(typeof(LossIncurredPayload))]
public string SerializeRequestToXml(Request request)
{
    // Instantiate the serializer
    XmlSerializer serializer = new XmlSerializer(typeof(Request));
    StringWriter stringWriter = new StringWriter();
    String xmlRequest;

    XmlSerializerNamespaces xmlSerializerNameSpaceValue = new XmlSerializerNamespaces();
    xmlSerializerNameSpaceValue.Add(String.Empty, String.Empty);
    serializer.Serialize(stringWriter, request, xmlSerializerNameSpaceValue);

    xmlRequest = stringWriter.ToString();

    xmlRequest = xmlRequest.Replace("utf-16", "utf-8");

    // Print request for testing
    Console.WriteLine("Request: " + xmlRequest);

    return xmlRequest;
}

我有什么想法可以让它发挥作用?当我将RequestPayload中的List类型更改为LossIncurredPayload时,序列化工作正常,但如果我这样做,那么我必须为每种类型都有一个特定的RequestPayload类,这就是我想要避免的。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

XmlIncludeAttribute课程上使用RequestPayload。为所有派生类型指定它。

[XmlInclude(typeof(LossIncurredPayload))]
public class RequestPayload
{
    [XmlElement]
    public List<Payload> BOM_Request { get; set; }
}