Generic 类型的序列化 JSON 对象错误

Serializing JSON object error of Generic type

我正在尝试序列化我在此处创建的对象:

using (MemoryStream memStream = new MemoryStream())
{
    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(CaseTreatment));
    ser.WriteObject(memStream, ct);
}

这里是ctList<CaseTreatment> ct = new List<CaseTreatment>();

每当我的代码命中 ser.WriteObject(memStream, ct); 时,我都会收到以下错误:

Type 'System.Collections.Generic.List`1[[FileUpload.Models.CaseTreatment, FileUpload,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' with data contract name 
'ArrayOfCaseTreatment:http://schemas.datacontract.org/2004/07/FileUpload.Models' is 
not expected. Consider using a DataContractResolver or add any types not known 
statically to the list of known types - for example, by using the KnownTypeAttribute 
attribute or by adding them to the list of known types passed to 
DataContractSerializer.

我的 CaseTreatment 对象如下所示:

[DataContract]
public class CaseTreatment
{
    [DataMember]
    public Bridge BridgeTreatment;
}

Bridge 看起来像这样:

[DataContract]
public class Bridge : CaseGeneric
{
    [DataMember]
    public bool IsBridgeTreatment;

    public Bridge(XElement treatment, IEnumerable<XElement> orderDetails)
    {
        var tn = Util.GetTitle(treatment);
        this.Instruction = Util.GetInstruction(tn);
        this.Id = 2;
        this.Name= "Bridge";
        this.Something = Util.GetSomething(tn);
    }

    public Bridge()
    {

    }

}

Something 是另一个对象:

[DataContract]
public class Something
{
    [DataMember]
    public string Number;
}

CaseGeneric 拥有所有这些:

[DataContract]
public class CaseGeneric
{
    [DataMember]
    public string Instruction;
    [DataMember]
    public int Id;
    [DataMember]
    public string Name;
    [DataMember]
    public List<Something> Something;
}

有人能帮忙吗?如果您需要更多信息,也请告诉我,我非常乐意 add/edit 任何事情或回答任何问题。我想我可能需要用 [KnownType(typeof(blah))] 装饰我的对象,我只是不知道在哪里和哪一个。

您正试图在列表中写入一个对象。尝试改变 DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(CaseTreatment));DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<CaseTreatment>));