Rename DataMember during Serialization
-
29-06-2021 - |
문제
I am trying to serialise a DataContract..... I would like to Rename the DataMember.
This is my DataContract
[DataContract(Name = "Sample")]
[Serializable]
public struct Sample
{
public string CompanyName;
public string AddressLine;
[DataMember(Name="AddressLineRename")]
public string AddressLine2;
public string City;
}
it is serialised to:
<Sample>
<CompanyName>aaa</CompanyName>
<AddressLine>16 aaaa</AddressLine>
<AddressLine2>Unit 66</AddressLine2>
<City>Houston</City>
</Sample>
what i need is:
<Sample>
<CompanyName>aaa</CompanyName>
<AddressLine>16 aaaa</AddressLine>
<AddressLineRename>Unit 66</AddressLineRename>
<City>Houston</City>
</Sample>
I want the "AddressLine2" to be serialised to "AddressLineRename".
Thanks.
해결책
This solved to rename the DataMember.
[DataMember(Order = 2, Name = "AddressLineRename", IsRequired = true)]
[XmlElement("AddressLineRename")]
public string AddressLine2;
다른 팁
You may need to implement ISerializable
to customize the serialization process yourself.
I think the code you would need to add would look something like:
public Sample(SerializationInfo info, StreamingContext context)
{
CompanyName = info.GetString("CompanyName");
// ...
AddressLine2 = info.GetString("AddressLineRename");
// ...
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("CompanyName", CompanyName);
// ...
info.AddValue("AddressLineRename", AddressLine2);
// ...
}
In my case I solved just adding the order parameter to DataMember
[DataMember(Order = 2, Name = "AddressLineRename")]
public string AddressLine2;
Don't know why..
제휴하지 않습니다 StackOverflow