开发者

In c# how do you make a field name different then when it is serialized?

开发者 https://www.devze.com 2023-02-04 17:08 出处:网络
I have a WCF service tha开发者_运维百科t I have built from an XSD from a client.The client XSD calls for a field named 3rdPartyTrackingNumber.Because in c# I can\'t have a field that starts with a num

I have a WCF service tha开发者_运维百科t I have built from an XSD from a client. The client XSD calls for a field named 3rdPartyTrackingNumber. Because in c# I can't have a field that starts with a number I have named it ThirdPartyTrackingNumber. Is there a meta tag or something that I can put on the column that will render it as 3rdartyTrackingNumber when serialized?

public class OSSShipmentGroup
{
    public string status { get; set; }
    public string shipmentNumber { get; set; }
    public object shipFrom { get; set; }
    public string carrierName { get; set; }

    [Some meta tag here]
    public string ThirdPartyTrackingNumber {get; set;}
    public OSSOrderDates dates { get; set; }
    public OSSOrderAddress[] address {get; set;}
    public OSSOrderShipmentItem[] containedItems { get; set; }
    public OSSShipmentInvoice[] invoice {get; set;}
}

I know I can implement ISerializable and make the changes in GetObjectData, but if it is only one field i was hoping I could just add a meta tag to the field.


It depends on what serializer you are using. For example if you are using DataContractSerializer which is the default in WCF basicHttpBinding and wsHttpBinding you could use the [DataMember] attribute

[DataMember(Name = "ABC")]
public string ThirdPartyTrackingNumber { get; set; }

If you are using XmlSerializer then the [XmlElement] attribute should do the job:

[XmlElement(ElementName = "ABC")]
public string ThirdPartyTrackingNumber { get; set; }


For WCF, the normal process is to annotate the class with [DataContract], an each property with [DataMember], which has an optional Name="foo" property.

Note that by adding the class-level attribute you are saying "I will explicitly tell you which members to serialize; you can't then just annotate the one you want to rename.

0

精彩评论

暂无评论...
验证码 换一张
取 消