gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 01:44:02 25 4
gpt4 key购买 nike

我正在编写一个返回动态构造的属性包的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com