In my code I have objects (and methods) that are working with quite a few IDs that are just simple Integers. To get a bit of help from the compiler when I'm setting values all over the place, I turned these simple ints into more strongly typed objects, kind of type aliases. Something like this:
public struct CustomId
{
private readonly int id;
public CustomId(int id) => this.id = id;
public static implicit operator int(CustomId cid) => cid.id;
public static implicit operator CustomId(int id) => new CustomId(id);
}
But as it's really just an int with a more specific name, I'd really like to serialize it just as an int so for example in JSON a Person would look like this:
{
"Name": "ASD",
"Id": 42 // this would be the serialized result of my CustomId
}
While I managed to build a custom JsonConverter for this case and it works fine if I'm using Newtonsoft JSON, I'm wondering if there is a better way of doing this, an attribute or an interface to implement (something from the System.Runtime.Serialization namespace), that most serializer frameworks will take into consideration, so I wouldn't have to write custom converters for JSON, XML, Protobuf, etc. serialization but could just rely on some generic solution.
TypeConverterto convert from and to a string if present. See Json.Net: Serialize/Deserialize property as a value, not as an object. I don't think there is a mechanism that works for all serializers however.XmlSerializerdoesn't support surrogates, for instance. Also, this question might be too broad for stackoverflow. Can you specify the serializer(s) you are using?XmlSerializerandDataContractSerializerby implementingIXmlSerializable-- but this will cause problems if you are usingDataContractJsonSerializer. So if you can restrict the scope of your question to specific serializers we may be able to give you some help.