5
votes

I have a very simple class called person.

public class Person{
   [DataMember(Name="MyName")]
   public string Name { get;set;}
}

If I try to serialize or de-serialize, everything works great. In the XML I can see a tag called "MyName" and in the object I see with the VS Intellisense a property called Name.

What I need now is to access, from the object, the serialized name of the property.

For example, I can do object.GetType().GetProperty("Name"); but if I try to do object.GetType().GetProperty("MyName"), the reflection says that the property does not exist. How I can read the serialized name of the property? Is there a way?

1
Are you trying to do this from the service side or the client side? - Tad Donaghe
From client side, and there is no way with the DataContractSerializer to read the attribute of the property. I tried also with XDocument and Linq. Any suggestions? - Raffaeu

1 Answers

3
votes

It seems that the only way is to access, using reflection, the attributes of the property in this way:

var att = myProperty.GetType().GetAttributes();
var attribute = property.GetCustomAttributes(false)[0] as DataMemberAttribute;
Console.WriteLine(attribute.Name);

This works on both, client and server, without the need of serialize and deserialize the object.