简体   繁体   English

Web API列表序列化

[英]web api list serialization

I want to serialize a list to xml (from a web-api method). 我想将一个列表序列化为xml(从一个web-api方法)。

public class Result
{
  public List<string> Users { get; set; }
}

So I get for example: 所以我得到例如:

<result>
  <user>Paul</user>
  <user>David</user>
  <user>Joan</user>
</result>

So far, I get: 到目前为止,我得到:

<result>
  <users>
    <user>Paul</user>
    <user>David</user>
    <user>Joan</user>
  </users>
</result>

How do I tell the serialization not to wrap the user list in a "users" tag? 如何告诉序列化不要将用户列表包装在“用户”标签中?

Thanks. 谢谢。

You could either derive from XmlObjectSerializer and implement your own XML Serializer (see here FMI) or else manipulate your type so it works with the default formatter. 你可以从任何派生XmlObjectSerializer和实现自己的XML序列化(见这里 FMI),或者操纵你的类型,因此它与默认的格式化工作。 Which isn't a great solution, but may work for a simple example, like so: 这不是一个很好的解决方案,但可能适用于一个简单的示例,如下所示:

public class Result : List<User>
{
    //Any user added to Result will be nested directly within Result in the XML
}

Further reading: 进一步阅读:

You need to replace default DataContractSerializer with XmlSerializer in Application_Start method. 您需要在Application_Start方法中用XmlSerializer替换默认的DataContractSerializer。

For whole project: 对于整个项目:

var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
xml.UseXmlSerializer = true;

For specific type: 对于特定类型:

var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
xml.SetSerializer<Result>(new XmlSerializer(typeof(Result)));

After this you can use attributes to format your xml output: 之后,您可以使用属性来格式化xml输出:

public class Result
{
  [XmlElement("user")]
  public List<string> Users { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM