Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot deserialize with XMLSerializer result from WCF webservice

Here is the code trying from compact framework to get 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();

It fails with {"There is an error in XML document (1, 2)."}

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

Table namespace is the same... I dont know whats wrong there...

UPDATE

Problem was that i had typeof(Table) not typeof(List<Table>) which works partially.. No error but created tables values are null!

like image 332
GorillaApe Avatar asked Aug 24 '11 16:08

GorillaApe


People also ask

Can I make XmlSerializer ignore the namespace on Deserialization?

Yes, you can tell the XmlSerializer to ignore namespaces during de-serialization. Note this is the kind of thing I meant. You are not telling the XmlSerializer to ignore namespaces - you are giving it XML that has no namespaces.

What is XmlSerializer C#?

XML serialization is the process of converting an object's public properties and fields to a serial format (in this case, XML) for storage or transport. Deserialization re-creates the object in its original state from the XML output.

How do you serialize an object in WCF?

This code constructs an instance of the DataContractSerializer that can be used only to serialize or deserialize instances of the Person class. DataContractSerializer dcs = new DataContractSerializer(typeof(Person)); // This can now be used to serialize/deserialize Person but not PurchaseOrder.

What is serialization and Deserialization in WCF?

WCF deserializes WCF messages into . Net objects and serializes . Net objects into WCF messages. WCF provides DataContractSerializer by default with a servicecontract. We can change this default serializer to a custom serializer like XMLSerializer.


1 Answers

The second parameter on the XmlSerializer constructor works for both serializing and deserializing. So, on the second parameter (the namespace) should be the same to the one being received. So you'll end up having:

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

Note the "WpfApplication1.Data.Model" at the end of the namespace string.

One way to get rid of the namespace thing. Is to specify on your model class (Table) that it should not use a namespace:

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

That way you don't need to specify the namespace for deserialization.

Hope it helps!

like image 137
Pablo G. Avatar answered Sep 30 '22 04:09

Pablo G.