Control JSON Serialization format of a custom type in .NET to produce a primitive string
Posted on 2010-04-08
Ok, EE .NET gurus, here is a Stackoverflow challenge.
I have a PhoneNumber class that stores a normalized string, and I've defined implicit operators for converting string to/from Phone to simplify treatment of the PhoneNumber as a string. I've also overridden the ToString() method to always return the cleaned version of the number (no hyphens or parentheses or spaces). In any views where I display the number, I explicitly call phone.Format(). The point is, I need to treat PhoneNumber as a string everwhere, but give me the ability for some validation and formatting as needed.
I would have thought there was an Object Oriented, simple C# solution to this. In C++, I'd inherit from the string type. But in C# I cannot derive from a sealed type (string) so I tried overriding ToString() and defining a string cast operator but it has not solved it.