c# - Web API - 动态到 XML 序列化

标签 c# xml dynamic asp.net-web-api

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

最佳答案

我们通过创建自定义 XML 格式化程序解决了这个问题。

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

Global.asax

GlobalConfiguration.Configuration.Formatters.Add(new CustomXmlFormatter());
GlobalConfiguration.Configuration.Formatters
    .Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);

创建一个名为 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);
                });
        }
    }
}

关于c# - Web API - 动态到 XML 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18951521/

相关文章:

java - 操作栏V7 : Why it doesn't work?

C - 无法打印动态数组值

c# - 如何检查动态是否为空。

c# - 为什么我使用 LINQ 时 Class Coupling 跳转?

c# - 具有自动代理登录的 WebBrowser 控件

c# - 我们还需要迭代器设计模式吗?

html - XSL 处理顺序

xml - 如何在 powershell 中打印 xml 元素的实际内容?

c# - 告诉 FxCop 另一个方法正在调用 dispose

javascript - 在javascript中获取动态属性