4

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

<MyCustomName>string value</MyCustomName>

OR

<MyCustomName>int</MyCustomName>

What I am ultimately trying to do is return a basic type with a Custom element name. I've tried the following:

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

But obviously you can't inherit a string or int value. Any help would be appreciated.

Devin
  • 61
  • 4

2 Answers2

2

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

ChrisWue
  • 18,612
  • 4
  • 58
  • 83
  • That may be the case, but I am also trying to utilize the JSON automatic serialization and if I just do the IXmlSerializable I'll loose that functionality. You would think there would be an easier way to do this. – Devin Mar 10 '12 at 18:45
0

If you are returning that type as a field in another class, then you could just use a surrogate property such as:

public TreeId Id { get; set; }

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

So instead of having to put DataContract on the TreeId class, the property IdSurrogate just handles translating it directly to a string value

BrandonAGr
  • 5,827
  • 5
  • 47
  • 72