0
votes

I have the following class defined

[DataContract(Name="PatientDocument")]
[KnownType(typeof(PatientDocument))]
public class PatientDocument 
{
    public PatientDocument()
    {
        //
        // TODO: Add constructor logic here
        //
    }
[DataMember]
public virtual String r_object_id { get; set; }

[DataMember]
public virtual int i_partition { get; set; }

[DataMember]
public virtual String nhs_consultant { get; set; }

. . . .

[DataMember]
public virtual String batch_name { get; set; }

[DataMember]
public virtual String document_type_code { get; set; }

[DataMember]
public virtual String nhs_patdoc_singlebodysite { get; set; }

}

and this is used in the following function

PatientDocuments pds            = null;
PatientDocument[] results       = null;
String PatientId                  = String.Empty;
StreamReader sr         = null;
DataContractJsonSerializer serializer = null;

try
{
    using ( MemoryStream ms = new MemoryStream())
    {
               pds = new PatientDocuments(Properties.Settings.Default.DataConnection);
               serializer  = new DataContractJsonSerializer(typeof(PatientDocument));

        PatientId   = context.Request.QueryString["PatientId"];
        results     = pds.Select(PatientId);

        serializer.WriteObject(ms,results);
        ms.Position = 0;
        sr = new StreamReader(ms);

        // now write to the context/browser

        context.Response.ContentType = "text/plain";
        context.Response.Write(sr.ReadToEnd());
    }

}
catch(System.Exception ex)
{
    throw;
}

The line

serializer.WriteObject(ms,results);

is failing with the message

Type 'PatientDocument[]' with data contract name 'ArrayOfPatientDocument:http://schemas.datacontract.org/2004/07/' is not expected. 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.

I can't see how to use KnownAttribute to allow me to serialize the class.

Using .Net 3.5

1
Are you sure you are not just trying to deserialise an array PatienDocument[] into a single PatienDocument. Can you post a snippet of XML that you are de serialising from.Ben Robinson

1 Answers

2
votes

You are trying to serialize an array of PatiantDocument objects using a serializer created for a single PatientDocument. Change your serializer initialization to:

serializer = new DataContractJsonSerializer(typeof(PatientDocument[]));

You don't need the KnownType attribute because you don't have any properties of non-primitive types (unless there are some in the snipped code).