使用DataContractSerializer处理序列化中的数组

本文关键字:数组 序列化 DataContractSerializer 处理 使用 | 更新日期: 2023-09-27 18:21:42

我有一个asp.net web api项目,我的用户模型有一个问题,它的属性是字符串[]角色,但没有按我想要的方式序列化。

用户型号:

[DataContract(Namespace = "")]
public class User
{
    [DataMember(Order = 0)]
    public string UserName { get; set; }  //ro
    [DataMember(Order = 1)]
    public int CustomerID { get; set; } //ro
    [DataMember(Order = 2)]
    public string Email { get; set; }
    [DataMember(Order = 3)]
    public string Phone { get; set; }
    [DataMember(Order = 4)]
    public string Mobile { get; set; }
    [DataMember(Order = 5)]
    public string FullName { get; set; }
    [DataMember(Order = 6)]
    public List<string> Roles { get; set; }
    [DataMember(Order = 7)]
    public string Culture { get; set; }
    [DataMember(Order = 8)]
    public string Language { get; set; }
    [DataMember(Order = 9)]
    public string TimeZone { get; set; }
    [DataMember(Order = 10)]
    public DateTime Created { get; set; } //ro
}

当我得到请求的结果时,它如下所示:-

<User xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <UserName>User1</UserName>
  <CustomerID>1234</CustomerID>
  <Email>abc@xyz.lmn</Email>
  <Phone/>
  <Mobile/>
  <FullName>XYZ</FullName>
  <Roles xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
    <d2p1:string>AdminRole</d2p1:string>
    <d2p1:string>AlertsRole</d2p1:string>
  </Roles>
  <Culture>en-IN</Culture>
  <Language>en</Language>
  <Created>2014-04-21T11:26:22</Created>
</User>

但是我想要如下的xml:-

<User xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <UserName>User1</UserName>
  <CustomerID>1234</CustomerID>
  <Email>abc@xyz.lmn</Email>
  <Phone/>
  <Mobile/>
  <FullName>XYZ</FullName>
  <Roles>
    <string>Role1</string>
    <string>Role2</string>
  </Roles>
  <Culture>en-IN</Culture>
  <Language>en</Language>
  <Created>2014-04-21T11:26:22</Created>
</User>

请提出我可以实施的任何解决方案。

提前感谢

使用DataContractSerializer处理序列化中的数组

您可以通过创建具有相同名称空间的集合类型来实现:

[CollectionDataContract(Namespace = "")]
public class StringList : List<string>
{
    public StringList() { }
    public StringList(IEnumerable<string> items) : base(items) { }
}
[DataContract(Namespace = "")]
public class User
{
    [DataMember(Order = 0)]
    public string UserName { get; set; }  //ro
    [DataMember(Order = 1)]
    public int CustomerID { get; set; } //ro
    [DataMember(Order = 2)]
    public string Email { get; set; }
    [DataMember(Order = 3)]
    public string Phone { get; set; }
    [DataMember(Order = 4)]
    public string Mobile { get; set; }
    [DataMember(Order = 5)]
    public string FullName { get; set; }
    [DataMember(Order = 6)]
    public StringList Roles { get; set; }
    [DataMember(Order = 7)]
    public string Culture { get; set; }
    [DataMember(Order = 8)]
    public string Language { get; set; }
    [DataMember(Order = 9)]
    public string TimeZone { get; set; }
    [DataMember(Order = 10)]
    public DateTime Created { get; set; } //ro
}