-2

I know that this question has already been asked, but I have strange problem and I can't figure out what to do:

public static class XmlHelper
{
    public static T Deserialize<T>(string xml)
    {
        using (var sr = new StringReader(xml))
        {
            var xs = new XmlSerializer(typeof(T));
            return (T)xs.Deserialize(sr);
        }
    }

    public static string Serialize(object o)
    {
        using (var sw = new StringWriter())
        {
            using (var xw = XmlWriter.Create(sw))
            {
                var xs = new XmlSerializer(o.GetType());
                xs.Serialize(xw, o);
                return sw.ToString();
            }
        }
    }
}

[Serializable]
public class MyClass
{
    public string Property1 {get;set;}
    public int Property2 {get;set;}
}

I'm serializing class:

var a = XmlHelper.Serialize(new MyClass{ Property1 = "a", Property2 = 3 });
var b = XmlHelper.Deserialize<object>(a);

Error: There is an error in XML document (1, 41).

Edit: I want to deserialize a as object, is it possible?

karaxuna
  • 26,752
  • 13
  • 82
  • 117

1 Answers1

1

You aren't passing in the correct type for serialization, change your code to:

public static string Serialize<T>(T o)
{
    using (var sw = new StringWriter())
    {
        using (var xw = XmlWriter.Create(sw))
        {
            var xs = new XmlSerializer(typeof(T));
            xs.Serialize(xw, o);
            return sw.ToString();
        }
    }
}
...
// we don't need to explicitly define MyClass as the type, it's inferred
var a = XmlHelper.Serialize(new MyClass{ Property1 = "a", Property2 = 3 });
var b = XmlHelper.Deserialize<MyClass>(a);
James
  • 80,725
  • 18
  • 167
  • 237
  • In real situation I want to serialize as MyClass and deserialize as object, is it possible? – karaxuna Jan 11 '13 at 14:29
  • @karaxuna That doesn't seem to make sense to me. Just treat it as an object? `object b = XmlHelper.Deserialize(a)`? Or do you mean you want to run the deserializer not knowing which type at compile time? – Chris Sinclair Jan 11 '13 at 14:50
  • Yes, when I'm deserializing it, I don't know it's type – karaxuna Jan 11 '13 at 14:57
  • AFAIK you can't do this. The serializer needs to know the destination type so it can map the properties correctly. Alternatively you could switch to using `JavaScriptSerializer`/`DataContractJsonSerializer` and serialize your data as JSON instead, that way you can deserialize without knowing the type. – James Jan 11 '13 at 15:37