Can you create a DataContract with a single Value Value Value Value?

I am curious if it is possible to create a DataContract that will serialize like this:

<MyCustomName>string value</MyCustomName> 

OR

 <MyCustomName>int</MyCustomName> 

What I'm ultimately trying to do is return the base type with the name of the user element. I tried the following:

 [DataContract(Name = "MyCustomName")] public class MyCustomName : String { } 

But obviously you cannot inherit a string or int value. Any help would be appreciated.

+4
source share
2 answers

I'm not sure if there is an easier way, but as far as I know, DataContractSerializer will respect it if your type implements IXmlSerializable . This way you can implement this interface and do your own serialization of MyCustomName

+2
source

If you return this type as a field in another class, you can simply use a surrogate property, for example:

 public TreeId Id { get; set; } [DataMember(Name = "Id")] private string IdSurrogate { get { return Id.ToString(); } set { Id = new TreeId(value); } } 

Thus, instead of putting the DataContract in the TreeId class, the IdSurrogate property simply processes it directly on the string value

0
source

Source: https://habr.com/ru/post/1400681/


All Articles