Web API - 动态到XML序列化

Jak*_*sky 9 c# xml dynamic asp.net-web-api

我正在编写一个Web API Web服务,它返回动态构造的属性包.是否有任何有效的序列化程序或如何将动态序列化为XML?我试图寻找任何好的建议,但没有发现任何可用的东西.

Jak*_*sky 22

我们通过创建自定义XML格式化程序来解决它.

这不是一个理想的解决方案,但它有效.

在里面 Global.asax

GlobalConfiguration.Configuration.Formatters.Add(new CustomXmlFormatter());
GlobalConfiguration.Configuration.Formatters
    .Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
Run Code Online (Sandbox Code Playgroud)

创建一个名为的新类 CustomXmlFormatter

using System;
using System.IO;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace EMP.WebServices.api.Formatters
{
    public class CustomXmlFormatter : MediaTypeFormatter
    {
        public CustomXmlFormatter()
        {
            SupportedMediaTypes.Add(
                new MediaTypeHeaderValue("application/xml"));
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml"));
        }

        public override bool CanReadType(Type type)
        {
            if (type == (Type)null)
                throw new ArgumentNullException("type");

            return true;
        }

        public override bool CanWriteType(Type type)
        {
            return true;
        }

        public override Task WriteToStreamAsync(Type type, object value,
            Stream writeStream, System.Net.Http.HttpContent content,
            System.Net.TransportContext transportContext)
        {
            return Task.Factory.StartNew(() =>
                {
                        var json = JsonConvert.SerializeObject(value);

                        var xml = JsonConvert
                            .DeserializeXmlNode("{\"Root\":" + json + "}", "");

                        xml.Save(writeStream);
                });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是一个很棒的答案.这可以保证,如果您还使用了Newtonsoft Json转换器,那么您最终将使用两种格式输出的相同数据 - 而无需标记所有模型. (5认同)