Unable to deserialize XMLSerializer result from WCF web service

Here is the code trying to create a compact structure to get an http service.

    List<Table> tables;
    using (Stream r = response.GetResponseStream())
    {
        XmlSerializer serializer = new XmlSerializer(typeof(Table),"http://schemas.datacontract.org/2004/07/");
        tables=(List<Table>) serializer.Deserialize(r);
    }

   response.Close();

Cannot execute {"There is an error (1, 2) in the XML document." }

{"<ArrayOfTable xmlns='http://schemas.datacontract.org/2004/07/WpfApplication1.Data.Model'> was not expected."}

The table namespace is the same ... I don't know what is wrong there ...

UPDATE

The problem was that I had typeof (Table) not typeof ( List<Table>), which works partially .. There are no errors, but the generated table values ​​are null!

+5
source share
3 answers

XmlSerializer , . , ( ) , . , :

XmlSerializer serializer = new XmlSerializer(typeof(Table),"http://schemas.datacontract.org/2004/07/WpfApplication1.Data.Model")

"WpfApplication1.Data.Model" .

. (Table), :

[DataContract(Namespace = "")]
public class Table { ... }

, .

, !

+5

, , . , DataContract/DataMember ( ) DataContractSerializer, , WCF XmlSerializerFormat, .

[System.ServiceModel.ServiceContract]
public interface IRestService
{
    [System.ServiceModel.OperationContract]
    // Added this attribute to use XmlSerializer instead of DataContractSerializer
    [System.ServiceModel.XmlSerializerFormat(
        Style=System.ServiceModel.OperationFormatStyle.Document)]
    [System.ServiceModel.Web.WebGet(
        ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Xml,
        UriTemplate = "xml/objects/{myObjectIdentifier}")]
    MyObject GetMyObject(int myObjectIdentifier);
}

:

public static T DeserializeTypedObjectFromXmlString<T>(string input)
{
    T result;

    try
    {
        System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(T));
        using (System.IO.TextReader textReader = new System.IO.StringReader(input))
        {
            result = (T)xs.Deserialize(textReader);
        }
    }
    catch
    {
        throw;
    }

    return result;
}
+4

Instead of returning a List, return an object that has one List property.

0
source

All Articles