Serializing Array with DataContractSerializer
I have an asp.net web api project and I have a problem with a user model that has the [] Roles string as a property that is not serialized as I want.
User Model:
[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
}
and when I get the result for the request it looks like this: -
<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>
but i want xml like this: -
<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>
Please suggest any solution I can implement.
Thank you in advance
+3
source to share
1 answer
You can do this by creating a collection type with the same namespace:
[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
}
+3
source to share