网页API - 动态到XML序列化 [英] Web API - Dynamic to XML serialization

查看:91
本文介绍了网页API - 动态到XML序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写在返回动态构造属性包一个Web API Web服务。是否有任何工作串行或方式如何序列动态到XML?我试图寻找任何好的建议,但没有发现任何有用的。

I am writing a Web API web service that is returning dynamically constructed property bag. Is there any working serializer or a way how to serialize dynamic to XML? I tried to look for any good suggestions but haven't found anything usable.

推荐答案

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

We solved it by creating a custom XML formatter.

这是不是一个理想的解决方案,但它的工作原理。

This isn't an ideal solution but it works.

的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);
                });
        }
    }
}

这篇关于网页API - 动态到XML序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆