简体   繁体   English

ServiceStack将xml反序列化为对象

[英]ServiceStack deserialize xml to object

My current method for deserialization looks like this: 我目前的反序列化方法如下所示:

public static object Deserialize(string xml, Type toType)
{
    object result = null;
    using (var stream = new MemoryStream())
    {
        var data = Encoding.UTF8.GetBytes(xml);
        stream.Write(data, 0, data.Length);
        stream.Position = 0;
        var deserializer = new DataContractSerializer(toType);
        result = deserializer.ReadObject(stream);
    }
    return result;
}

Can I use ServiceStack's deserialization here somehow? 我能以某种方式在这里使用ServiceStack的反序列化吗? Maybe I should be using something other than the FromXml method? 也许我应该使用除FromXml方法之外的其他东西? The important part to me is that I need to be able to pass in the System.Type parameter (toType) but have the result be of type object . 对我来说重要的是我需要能够传入System.Type参数(toType),但结果是object类型。

This obviously doesn't work: 这显然不起作用:

public static object Deserialize(string xml, Type toType)
{
    object result = null;
    result = xml.FromXml<toType>();
    return result;
}

Neither does this: 这也不是:

public static object Deserialize(string xml, Type toType)
{
    object result = null;
    result = xml.FromXml<object>();
    return result;
}

The API to deserialize in ServiceStack.Text is: ServiceStack.Text中反序列化的API是:

var dto = XmlSerializer.Deserialize(xml, toType);

But for XML it's just a wrapper around .NET's Xml DataContractSerializer so it's not much of a benefit. 但是对于XML来说,它只是.NET的Xml DataContractSerializer的包装器,所以它没有多大好处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM