gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:10:26 25 4
gpt4 key购买 nike

我有一个 asp.net web api 项目,我遇到了用户模型的问题,该模型具有 string[] 角色作为属性,未按我的意愿序列化。

用户模型:

[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>

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

提前致谢

最佳答案

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

[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
}

关于c# - 使用 DataContractSerializer 处理序列化中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25806836/

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