C#WebAPI序列化字符串列表

时间:2013-11-13 00:42:11

标签: c# asp.net xml collections asp.net-web-api

这应该是一个相对简单的问题,我在网上讨论了一段时间,仍然无法找到解决方案。

现在我的webapi会返回这样的输出

<Merchant>
    <Cuisine xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
        <d3p1:string>Japanese</d3p1:string>
        <d3p1:string>Korean</d3p1:string>
        <d3p1:string>French</d3p1:string>
    </Cuisine>
</Merchant>

我希望它像这样返回

<Merchant>
    <Cuisines>
        <Cuisine>Japanese</Cuisine>
        <Cuisine>Korean</Cuisine>
        <Cuisine>French</Cuisine>
    </Cuisines>
</Merchant>

完成此类任务的最简单方法是什么?

所以基本上我想做两件事

1)摆脱命名空间xmlns:d3p1 =“http://schemas.microsoft.com/2003/10/Serialization/Arrays” 2)从

更改outter元素的名称
<Cuisine> 

<Cuisines> 

3)从

更改内部元素的名称
<d2p1:string>

<Cuisine>

我在Merchant类中的数据库就像这样

[DataMember(EmitDefaultValue = false)]
public List<String> WebCuisine { get; set; }

先谢谢你

2 个答案:

答案 0 :(得分:3)

您必须使用自己的序列化程序。

  1. 创建数据结构

    [XmlRoot("Merchant")]
    public class Merchant
    {
        [XmlArray("Cuisines"), XmlArrayItem("Cuisine")]
        public List<String> WebCuisine { get; set; }
    }
    
  2. 创建一个继承自XmlObjectSerializer

    的类
    public class MerchantSerializer : XmlObjectSerializer
    {
        XmlSerializer serializer;
    
        public MerchantSerializer()
        {
            this.serializer = new XmlSerializer(typeof(Merchant));
        }
    
        public override void WriteObject(XmlDictionaryWriter writer, object graph)
        {
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");
            serializer.Serialize(writer, graph, ns);
        }
    
        public override bool IsStartObject(XmlDictionaryReader reader)
        {
            throw new NotImplementedException();
        }
    
        public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName)
        {
            throw new NotImplementedException();
        }
    
        public override void WriteEndObject(XmlDictionaryWriter writer)
        {
            throw new NotImplementedException();
        }
    
        public override void WriteObjectContent(XmlDictionaryWriter writer, object graph)
        {
            throw new NotImplementedException();
        }
    
        public override void WriteStartObject(XmlDictionaryWriter writer, object graph)
        {
            throw new NotImplementedException();
        }
    }
    
  3. 正如你所看到的,我只对写作感兴趣,而不是阅读。但是,如果需要,可以轻松实现ReadObject。

    1. public static void Register(HttpConfiguration config)的WebApiConfig中添加

        config.Formatters.XmlFormatter.SetSerializer<Merchant>(new MerchantSerializer());
      
    2. 你应该得到

      <Merchant>
         <Cuisines>
             <Cuisine>Japanese</Cuisine>
             <Cuisine>Korean</Cuisine>
             <Cuisine>French</Cuisine>
         </Cuisines>
      </Merchant>
      

答案 1 :(得分:0)

我不知道这是否会对任何人有所帮助,但我将商家序列化程序修改为通用序列化程序

using System;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Serialization;

namespace NoNamespaceXml
{

  public class GenericSerializer : XmlObjectSerializer
  {        
    #region Private Variables
    private XmlSerializer serializer;
    #endregion

    #region Constructor
    /// <summary>
    /// Create a new instance of a GenericSerializer  
    /// </summary>
    /// <param name="objectToSerialize"></param>
    public GenericSerializer (object objectToSerialize)
    {
        // If the objectToSerialize object exists
        if (objectToSerialize != null)
        {
            // Create the Serializer
            this.Serializer = new XmlSerializer(objectToSerialize.GetType());
        }
    }
    #endregion

    #region Methods

        #region IsStartObject(XmlDictionaryReader reader)
        /// <summary>
        /// This method Is Start Object
        /// </summary>
        public override bool IsStartObject(XmlDictionaryReader reader)
        {
            throw new NotImplementedException();
        }
        #endregion

        #region ReadObject(XmlDictionaryReader reader, bool verifyObjectName)
        /// <summary>
        /// This method Read Object
        /// </summary>
        public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName)
        {
            throw new NotImplementedException();
        }
        #endregion

        #region WriteEndObject(XmlDictionaryWriter writer)
        /// <summary>
        /// This method Write End Object
        /// </summary>
        public override void WriteEndObject(XmlDictionaryWriter writer)
        {
            throw new NotImplementedException();
        }
        #endregion

        #region WriteObject(XmlDictionaryWriter writer, object graph)
        /// <summary>
        /// This method Write Object
        /// </summary>
        public override void WriteObject(XmlDictionaryWriter writer, object graph)
        {
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");
            serializer.Serialize(writer, graph, ns);
        }
        #endregion

        #region WriteObjectContent(XmlDictionaryWriter writer, object graph)
        /// <summary>
        /// This method Write Object Content
        /// </summary>
        public override void WriteObjectContent(XmlDictionaryWriter writer, object graph)
        {
            throw new NotImplementedException();
        }
        #endregion

        #region WriteStartObject(XmlDictionaryWriter writer, object graph)
        /// <summary>
        /// This method Write Start Object
        /// </summary>
        public override void WriteStartObject(XmlDictionaryWriter writer, object graph)
        {
            throw new NotImplementedException();
        }
        #endregion

    #endregion

    #region Properties

        #region HasSerializer
        /// <summary>
        /// This property returns true if this object has a 'Serializer'.
        /// </summary>
        public bool HasSerializer
        {
            get
            {
                // initial value
                bool hasSerializer = (this.Serializer != null);

                // return value
                return hasSerializer;
            }
        }
        #endregion

        #region Serializer
        /// <summary>
        //  This property gets or sets the value for 'Serializer'.
        /// </summary>
        public XmlSerializer Serializer
        {
            get { return serializer; }
            set { serializer = value; }
        }
        #endregion

    #endregion

}
#endregion

}

然后你要做的就是注册你想要使用这个序列化器的任何类型:

// Set the Serializer for certain objects
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SetSerializer<NetworkSearchResponse>(serializer);
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SetSerializer<SynxiBooleanResponse>(serializer);